Find the Longest Substring Having K Distinct Vowels in Java

Our primary focus is on the set of vowels because the set of vowels is usually essential to many string manipulation problems, and one such problem is the problem of identifying the longest substring of the given string containing precisely K different vowels. The problem requires a good understanding of the working of string handling, sliding windows and use of hash maps.

Problem Statement

Enumerated string s and integer K are input data of the problem; the task is to determine the maximal length of substring including exactly K different vowels. If there is no such a word as string, then return 0.

Approach 1: Brute-Force Method

The method of using brute force is rather effective, though highly unproductive. It comprises testing all the potential sub-strings of the given string, making a count of the total though different vowels found in the sub-string. In case a substring comprises exactly K unique vowel(s), its size is compared to the previous maximum substring's size.

File Name: LongestKDistinctVowels.java

Output:

 
Longest substring length with 2 distinct vowels: 4   

Time Complexity: O(N^3)

Space Complexity: O(K)

Approach 2: Optimized Sliding Window Approach

Optimized Sliding Window Approach Here, the algorithm is modified a little where we store the largest n values instead of just storing one value.

It is important to note that the brute force method is very time-consuming and recommended only for small strings. However, to improve, instead of just two for-loops, there is what is called the sliding window technique accompanied by a hash map where we have to keep track of the vowels in the current window.

Sliding Window with HashMap

The strategy is simply to slide the window wider until getting K different vowels, and then slide the window narrower to look for a larger valid window. We utilize a hash map to keep the current count of each vowel in the current window.

File Name: LongestKDistinctVowelsOptimized.java

Output:

 
Longest substring length with 2 distinct vowels: 4   

Time Complexity: O(N)

Space Complexity: O(K)

Conclusion

The problem of determining the longest substring with K distinct vowels can be solved in different ways, which makes the problem quite engaging. The said solution is simple but not scalable for large inputs because of the high time complexity required for computations.

The second solution is the sliding window technique with the help of a hash map, improving the result and being able to work with more significant strings. Which of the two methods to use depends on the problem and its solution, as well as the time allowed for their implementation in competitive programming and practical situations.