Longest substring consisting of vowels using Binary Search
Last Updated :
03 Mar, 2023
Given string str of length N, the task is to find the longest substring which contains only vowels using the Binary Search technique.
Examples:
Input: str = "baeicba"
Output: 3
Explanation:
Longest substring which contains vowels only is "aei".
Input: str = "aeiou"
Output: 5
Approach: Refer to the Longest substring of vowels for an approach in O(N) complexity.
Binary Search Approach: In this article, we are using a Binary Search based approach:
Follow the steps below to solve the problem:
- Apply binary search on the lengths ranging from 1 to N.
- For each mid-value check if there exists a substring of length mid consisting only of vowels in that substring.
- If there exists a substring of length mid, then update the value of max and update l as mid+1 to check if a substring of length greater than mid exists or not which consists only of vowels.
- If no such substring of length mid exists, update r as mid-1 to check if a substring of length smaller than mid exists or not which consists only of vowels.
- Repeat the above three steps until l is less than or equal to r.
- Return the max length obtained finally.
Below is the implementation of the above approach:
C++
// C++ implementation of
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check if a character
// is vowel or not
bool vowel(int vo)
{
// 0-a 1-b 2-c and so on 25-z
if (vo == 0 || vo == 4
|| vo == 8 || vo == 14
|| vo == 20)
return true;
else
return false;
}
// Function to check if any
// substring of length k exists
// which contains only vowels
bool check(string s, int k)
{
vector<int> cnt(26, 0);
for (int i = 0; i < k - 1; i++) {
cnt[s[i] - 'a']++;
}
// Applying sliding window to get
// all substrings of length K
for (int i = k - 1; i < s.size();
i++) {
cnt[s[i] - 'a']++;
int flag1 = 0;
for (int j = 0; j < 26; j++) {
if (vowel(j) == false
&& cnt[j] > 0) {
flag1 = 1;
break;
}
}
if (flag1 == 0)
return true;
// Remove the occurrence of
// (i-k+1)th character
cnt[s[i - k + 1] - 'a']--;
}
return false;
}
// Function to perform Binary Search
int longestSubstring(string s)
{
int l = 1, r = s.size();
int maxi = 0;
// Doing binary search on the lengths
while (l <= r) {
int mid = (l + r) / 2;
if (check(s, mid)) {
l = mid + 1;
maxi = max(maxi, mid);
}
else
r = mid - 1;
}
return maxi;
}
// Driver Code
int main()
{
string s = "sedrewaefhoiu";
cout << longestSubstring(s);
return 0;
}
Java
// Java implementation of
// the above approach
import java.util.*;
class GFG{
// Function to check if a character
// is vowel or not
static boolean vowel(int vo)
{
// 0-a 1-b 2-c and so on 25-z
if (vo == 0 || vo == 4 ||
vo == 8 || vo == 14 ||
vo == 20)
return true;
else
return false;
}
// Function to check if any
// subString of length k exists
// which contains only vowels
static boolean check(String s, int k)
{
int []cnt = new int[26];
for (int i = 0; i < k - 1; i++)
{
cnt[s.charAt(i) - 'a']++;
}
// Applying sliding window to get
// all subStrings of length K
for (int i = k - 1; i < s.length(); i++)
{
cnt[s.charAt(i) - 'a']++;
int flag1 = 0;
for (int j = 0; j < 26; j++)
{
if (vowel(j) == false && cnt[j] > 0)
{
flag1 = 1;
break;
}
}
if (flag1 == 0)
return true;
// Remove the occurrence of
// (i-k+1)th character
cnt[s.charAt(i - k + 1) - 'a']--;
}
return false;
}
// Function to perform Binary Search
static int longestSubString(String s)
{
int l = 1, r = s.length();
int maxi = 0;
// Doing binary search on the lengths
while (l <= r)
{
int mid = (l + r) / 2;
if (check(s, mid))
{
l = mid + 1;
maxi = Math.max(maxi, mid);
}
else
r = mid - 1;
}
return maxi;
}
// Driver Code
public static void main(String[] args)
{
String s = "sedrewaefhoiu";
System.out.print(longestSubString(s));
}
}
// This code is contributed by sapnasingh4991
Python3
# Python3 implementation of
# the above approach
# Function to check if a character
# is vowel or not
def vowel(vo):
# 0-a 1-b 2-c and so on 25-z
if (vo == 0 or vo == 4 or
vo == 8 or vo == 14 or
vo == 20):
return True
else:
return False
# Function to check if any
# substring of length k exists
# which contains only vowels
def check(s, k):
cnt = [0] * 26
for i in range (k - 1):
cnt[ord(s[i]) - ord('a')] += 1
# Applying sliding window to get
# all substrings of length K
for i in range (k - 1, len(s)):
cnt[ord(s[i]) - ord('a')] += 1
flag1 = 0
for j in range (26):
if (vowel(j) == False
and cnt[j] > 0):
flag1 = 1
break
if (flag1 == 0):
return True
# Remove the occurrence of
# (i-k+1)th character
cnt[ord(s[i - k + 1]) - ord('a')] -= 1
return False
# Function to perform Binary Search
def longestSubstring(s):
l = 1
r = len(s)
maxi = 0
# Doing binary search on the lengths
while (l <= r):
mid = (l + r) // 2
if (check(s, mid)):
l = mid + 1
maxi = max(maxi, mid)
else:
r = mid - 1
return maxi
# Driver Code
if __name__ == "__main__":
s = "sedrewaefhoiu"
print (longestSubstring(s))
# This code is contributed by Chitranayal
C#
// C# implementation of
// the above approach
using System;
class GFG{
// Function to check if a character
// is vowel or not
static bool vowel(int vo)
{
// 0-a 1-b 2-c and so on 25-z
if (vo == 0 || vo == 4 ||
vo == 8 || vo == 14 ||
vo == 20)
return true;
else
return false;
}
// Function to check if any
// subString of length k exists
// which contains only vowels
static bool check(String s, int k)
{
int []cnt = new int[26];
for (int i = 0; i < k - 1; i++)
{
cnt[s[i] - 'a']++;
}
// Applying sliding window to get
// all subStrings of length K
for (int i = k - 1; i < s.Length; i++)
{
cnt[s[i] - 'a']++;
int flag1 = 0;
for (int j = 0; j < 26; j++)
{
if (vowel(j) == false && cnt[j] > 0)
{
flag1 = 1;
break;
}
}
if (flag1 == 0)
return true;
// Remove the occurrence of
// (i-k+1)th character
cnt[s[i - k + 1] - 'a']--;
}
return false;
}
// Function to perform Binary Search
static int longestSubString(String s)
{
int l = 1, r = s.Length;
int maxi = 0;
// Doing binary search on the lengths
while (l <= r)
{
int mid = (l + r) / 2;
if (check(s, mid))
{
l = mid + 1;
maxi = Math.Max(maxi, mid);
}
else
r = mid - 1;
}
return maxi;
}
// Driver Code
public static void Main(String[] args)
{
String s = "sedrewaefhoiu";
Console.Write(longestSubString(s));
}
}
// This code is contributed by sapnasingh4991
JavaScript
// JavaScript code to implement above approach.
// Function to check if a character
// is vowel or not
function vowel(vo) {
// 0-a 1-b 2-c and so on 25-z
if (vo == 0 || vo == 4 || vo == 8 || vo == 14 || vo == 20) {
return true;
} else {
return false;
}
}
// Function to check if any
// substring of length k exists
// which contains only vowels
function check(s, k) {
let cnt = new Array(26).fill(0);
for (let i = 0; i < k - 1; i++) {
cnt[s.charCodeAt(i) - 'a'.charCodeAt(0)] += 1;
}
// Applying sliding window to get
// all substrings of length K
for (let i = k - 1; i < s.length; i++) {
cnt[s.charCodeAt(i) - 'a'.charCodeAt(0)] += 1;
let flag1 = 0;
for (let j = 0; j < 26; j++) {
if (vowel(j) == false && cnt[j] > 0) {
flag1 = 1;
break;
}
}
if (flag1 == 0) {
return true;
}
// Remove the occurrence of
// (i-k+1)th character
cnt[s.charCodeAt(i - k + 1) - 'a'.charCodeAt(0)] -= 1;
}
return false;
}
// Function to perform Binary Search
function longestSubstring(s) {
let l = 1;
let r = s.length;
let maxi = 0;
// Doing binary search on the lengths
while (l <= r) {
let mid = Math.floor((l + r) / 2);
if (check(s, mid)) {
l = mid + 1;
maxi = Math.max(maxi, mid);
} else {
r = mid - 1;
}
}
return maxi;
}
// Driver Code
let s = "sedrewaefhoiu";
console.log(longestSubstring(s));
// contributed by adityasha4x71
Time Complexity: O(NlogN)
Auxiliary Space: O(26) => O(1), no extra space is required, so it is a constant.
Similar Reads
Longest Subsequence of a String containing only vowels Given a string str containing only alphabets, the task is to print the longest subsequence of the string str containing only vowels.Examples: Input: str = "geeksforgeeks" Output: eeoee Explanation: "eeoee" is the longest subsequence of the string containing only vowels. Input: str = "HelloWorld" Out
5 min read
Count of substrings consisting only of vowels Given a string S, the task is to count all substrings which contain only vowels. Examples: Input: S = "geeksforgeeks" Output: 7 Explanation: Substrings {"e", "ee", "e", "o", "e", "ee", "e"} consists only of vowels. Input: S = "aecui" Output: 6 Explanation: Substrings {"a", "ae", "e", "u", "ui", "i"}
11 min read
Find the Longest Common Substring using Binary search and Rolling Hash Given two strings X and Y, the task is to find the length of the longest common substring. Examples: Input: X = âGeeksforGeeksâ, y = âGeeksQuizâ Output: 5 Explanation: The longest common substring is âGeeksâ and is of length 5. Input: X = âabcdxyzâ, y = âxyzabcdâ Output: 4 Explanation: The longest c
11 min read
Longest Common Prefix using Binary Search Given an array of strings arr[], the task is to return the longest common prefix among each and every strings present in the array. If thereâs no prefix common in all the strings, return "".Examples:Input: arr[] = [âgeeksforgeeksâ, âgeeksâ, âgeekâ, âgeezerâ]Output: "gee"Explanation: "gee" is the lon
8 min read
Longest Substring having equal count of Vowels and Consonants Given a string S consisting of lowercase English letters, the task is to find the length of the longest substring from the given string, having an equal number of vowels and consonants. Examples: Input: S = "geeksforgeeks" Output: 10 Explanation: The substring "eeksforgee" consists of 5 vowels and 5
7 min read
Find unique substrings consisting of only vowels from given String Given string str of size N consisting of uppercase and lowercase English letters. The task is to find all unique substrings containing only vowels. Examples: Input: str = "GeeksforGeeks"Output: "ee" , "e", "o"Explanation: There are multiple occurrences of some of the substrings like "ee" but these a
14 min read