Count of K length substring containing at most X distinct vowels
Last Updated :
12 Jan, 2022
Given string str of size N containing both uppercase and lowercase letters, and two integers K and X. The task is to find the count of substrings of size K containing at most X distinct vowels.
Examples:
Input: str = "TrueGoik", K = 3, X = 2
Output: 6
Explanation: The five such substrings are "Tru", "rue", "ueG", "eGo", "Goi" and"oik".
Input: str = "GeeksForGeeks", K = 2, X = 2
Output: 12
Explanation: "Ge", "ee", "ek", "ks", "sf", "fo", "or", "rG", "Ge", "ee", "ek" and "ks".
Approach: To solve the problem, first one have to generate all the substrings of length K. Then in each substring check if number of distinct vowels is less than X or not. Follow the steps mentioned below.
- First generate all substrings of length K starting from each index i in [0, N - K].
- Then for each substring of length K, do the following:
- Keep a hash to store the occurrences of unique vowels.
- Check if a new character in the substring is a vowel or not.
- If it is a vowel, increment its occurrence in the hash and keep a count of distinct vowels found
- Now for each substring, if the distinct count of vowels is less than or equal to X, increment the final count.
- When all the substrings have been considered, print the final count.
Below is the implementation of the above approach:
C++
// C++ code to implement above approach
#include <bits/stdc++.h>
using namespace std;
#define MAX 128
// Function to check whether
// a character is vowel or not
bool isVowel(char x)
{
return (x == 'a' || x == 'e' || x == 'i'
|| x == 'o' || x == 'u' ||
x == 'A' || x == 'E' || x == 'I'
|| x == 'O' || x == 'U');
}
int getIndex(char ch)
{
return (ch - 'A' > 26 ? ch - 'a' :
ch - 'A');
}
// Function to find the count of K length
// substring with at most x distinct vowels
int get(string str, int k, int x)
{
int n = str.length();
// Initialize result
int res = 0;
// Consider all substrings
// beginning with str[i]
for (int i = 0; i <= n - k; i++) {
int dist_count = 0;
// To store count of characters
// from 'a' to 'z'
vector<int> cnt(26, 0);
// Consider all substrings
// between str[i..j]
for (int j = i; j < i + k; j++) {
// If this is a new vowels
// for this substring,
// increment dist_count.
if (isVowel(str[j])
&& cnt[getIndex(str[j])]
== 0) {
dist_count++;
}
// Increment count of
// current character
cnt[getIndex(str[j])]++;
}
// If count of distinct vowels
// in current substring
// of length k is less than
// equal to x, then increment result.
if (dist_count <= x)
res++;
}
return res;
}
// Driver code
int main(void)
{
string s = "TrueGoik";
int K = 3, X = 2;
cout << get(s, K, X);
return 0;
}
Java
// Java code to implement above approach
import java.util.Arrays;
class GFG {
static int MAX = 128;
// Function to check whether
// a character is vowel or not
static boolean isVowel(char x) {
return (x == 'a' || x == 'e' || x == 'i'
|| x == 'o' || x == 'u' ||
x == 'A' || x == 'E' || x == 'I'
|| x == 'O' || x == 'U');
}
static int getIndex(char ch) {
return (ch - 'A' > 26 ? ch - 'a' : ch - 'A');
}
// Function to find the count of K length
// substring with at most x distinct vowels
static int get(String str, int k, int x) {
int n = str.length();
// Initialize result
int res = 0;
// Consider all substrings
// beginning with str[i]
for (int i = 0; i <= n - k; i++) {
int dist_count = 0;
// To store count of characters
// from 'a' to 'z'
int[] cnt = new int[26];
Arrays.fill(cnt, 0);
// Consider all substrings
// between str[i..j]
for (int j = i; j < i + k; j++) {
// If this is a new vowels
// for this substring,
// increment dist_count.
if (isVowel(str.charAt(j))
&& cnt[getIndex(str.charAt(j))] == 0) {
dist_count++;
}
// Increment count of
// current character
cnt[getIndex(str.charAt(j))]++;
}
// If count of distinct vowels
// in current substring
// of length k is less than
// equal to x, then increment result.
if (dist_count <= x)
res++;
}
return res;
}
// Driver code
public static void main(String args[]) {
String s = "TrueGoik";
int K = 3, X = 2;
System.out.println(get(s, K, X));
}
}
// This code is contributed by saurabh_jaiswal.
Python3
# Python code for the above approach
# Function to check whether
# a character is vowel or not
def isVowel(x):
return (x == 'a' or x == 'e' or x == 'i' or x == 'o'
or x == 'u' or x == 'A' or x == 'E' or x == 'I'
or x == 'O' or x == 'U')
def getIndex(ch):
return (ord(ch) - ord('a')) if (ord(ch) - ord('A')) > 26 else (ord(ch) - ord('A'))
# Function to find the count of K length
# substring with at most x distinct vowels
def get(str, k, x):
n = len(str)
# Initialize result
res = 0
# Consider all substrings
# beginning with str[i]
for i in range(n - k + 1):
dist_count = 0
# To store count of characters
# from 'a' to 'z'
cnt = [0] * 26
# Consider all substrings
# between str[i..j]
for j in range(i, i + k):
# If this is a new vowels
# for this substring,
# increment dist_count.
if (isVowel(str[j]) and cnt[getIndex(str[j])] == 0):
dist_count += 1
# Increment count of
# current character
cnt[getIndex(str[j])] += 1
# If count of distinct vowels
# in current substring
# of length k is less than
# equal to x, then increment result.
if (dist_count <= x):
res += 1
return res
# Driver code
s = "TrueGoik"
K = 3
X = 2
print(get(s, K, X))
# This code is contributed by Saurabh Jaiswal
C#
// C# code to implement above approach
using System;
class GFG {
// Function to check whether
// a character is vowel or not
static bool isVowel(char x)
{
return (x == 'a' || x == 'e' || x == 'i' || x == 'o'
|| x == 'u' || x == 'A' || x == 'E'
|| x == 'I' || x == 'O' || x == 'U');
}
static int getIndex(char ch)
{
return (ch - 'A' > 26 ? ch - 'a' : ch - 'A');
}
// Function to find the count of K length
// substring with at most x distinct vowels
static int get(string str, int k, int x)
{
int n = str.Length;
// Initialize result
int res = 0;
// Consider all substrings
// beginning with str[i]
for (int i = 0; i <= n - k; i++) {
int dist_count = 0;
// To store count of characters
// from 'a' to 'z'
int[] cnt = new int[26];
// Arrays.fill(cnt, 0);
// Consider all substrings
// between str[i..j]
for (int j = i; j < i + k; j++) {
// If this is a new vowels
// for this substring,
// increment dist_count.
if (isVowel(str[j])
&& cnt[getIndex(str[j])] == 0) {
dist_count++;
}
// Increment count of
// current character
cnt[getIndex(str[j])]++;
}
// If count of distinct vowels
// in current substring
// of length k is less than
// equal to x, then increment result.
if (dist_count <= x)
res++;
}
return res;
}
// Driver code
public static void Main()
{
string s = "TrueGoik";
int K = 3, X = 2;
Console.WriteLine(get(s, K, X));
}
}
// This code is contributed by ukasp.
JavaScript
<script>
// JavaScript code for the above approach
// Function to check whether
// a character is vowel or not
function isVowel(x) {
return (x == 'a' || x == 'e' || x == 'i' || x == 'o'
|| x == 'u' || x == 'A' || x == 'E' || x == 'I'
|| x == 'O' || x == 'U');
}
function getIndex(ch) {
return ((ch.charCodeAt(0) - 'A'.charCodeAt(0)) > 26 ? (ch.charCodeAt(0) - 'a'.charCodeAt(0)) :
(ch.charCodeAt(0) - 'A'.charCodeAt(0)));
}
// Function to find the count of K length
// substring with at most x distinct vowels
function get(str, k, x) {
let n = str.length;
// Initialize result
let res = 0;
// Consider all substrings
// beginning with str[i]
for (let i = 0; i <= n - k; i++) {
let dist_count = 0;
// To store count of characters
// from 'a' to 'z'
let cnt = new Array(26).fill(0);
// Consider all substrings
// between str[i..j]
for (let j = i; j < i + k; j++) {
// If this is a new vowels
// for this substring,
// increment dist_count.
if (isVowel(str[j])
&& cnt[getIndex(str[j])]
== 0) {
dist_count++;
}
// Increment count of
// current character
cnt[getIndex(str[j])]++;
}
// If count of distinct vowels
// in current substring
// of length k is less than
// equal to x, then increment result.
if (dist_count <= x)
res++;
}
return res;
}
// Driver code
let s = "TrueGoik";
let K = 3, X = 2;
document.write(get(s, K, X));
// This code is contributed by Potta Lokesh
</script>
Time Complexity: O(N * K)
Auxiliary Space: O(N * K)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read