Find Longest Substring Containing Exactly K-Vowels in Java

It is a problem frequently asked in interviews of top IT companies like Google, Amazon, TCS, Accenture, etc. By solving the problem, one wants to check the logical ability, critical thinking, and problem-solving skill of the interviewee. So, in this section, we are going to find longest substring containing exactly k-vowels in Java with different approaches and logic. Also, we will create Java programs for the same.

Problem Statement

We have given a string (str) having both uppercase and lowercase letters, and an integer K. The task is to find the longest substring containing exactly K vowels (maybe repetitive).

Solution to The Problem

Naïve Approach

The task is to determine which substring of a given string is the longest and contains precisely K vowels. As defined, vowels are the letters a, e, i, o, and u. We need to get the length of the longest substring that has exactly K vowels given a string s and an integer K. Return 0 if there is not a substring of that kind.

File Name: LongestSubstringKBruteForce.java

Output:

 
Longest Substring Length: 9   

Explanation

Two nested loops are employed in this brute-force method to produce every conceivable substring. We use the isVowel() method to count the number of vowels for each substring.

We update the maximum length so far found if the count equals K. The temporal complexity of this method is O(n^2), where n is the string's length. Although it's not the fastest way, it guarantees accuracy.

2. Sliding Window Method

This optimized approach maintains a window that slides over the string, adjusting its size to ensure it contains precisely K vowels.

File Name: LongestSubstringKSlidingWindow.java

Output:

 
Longest Substring Length: 9   

Explanation

We keep a window defined by two pointers, left and right, in the sliding window approach. By turning to the right, we enlarge the window and count the vowels within. Should the number of vowels surpass K, the window will be shrunk from the left by advancing the left cursor until the number of vowels is precisely K.

The most extended admissible window is noted in full. With this approach, the time complexity is reduced to O(n), increasing its efficiency for longer strings.

3. Using HashMap Approach

This approach tracks the occurrence of each vowel within the current window using a HashMap.

File Name: LongestSubstringKHashMap.java

Output:

 
Longest Substring Length: 9   

Explanation

Using a HashMap, we track each vowel's occurrence in the active window in the HashMap method. It enables us to control the number of vowels while adjusting the window effectively.

The sliding window approach and the rationale for extending and contracting the window are identical, but the usage of the HashMap gives you better control over the vowels. Even with extra constraints, this strategy can be more flexible, but the temporal complexity is still O(n).