Count Substrings with at least one occurrence of first K alphabet
Last Updated : 14 Sep, 2023
Given a string S of size N and a positive integer K. The given string only consists of the first K English lowercase alphabets. The task is to find the number of substrings that contain at least one occurrence of all these K characters.
Examples:
Input: S = "abcabc", K = 3
Output: 10
Explanation: The substrings containing at least one occurrence of the first three characters of English lowercase alphabets (a, b and c) are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc".
Input: S = "aaacb", K = 4
Output: 0
Explanation: There is no substring that contains at least one occurrence of all first K characters of English lowercase alphabets (a, b, c and d)
An approach using Hashing and Two-Pointer approach:
The idea is to keep a two-pointer say start and end at the beginning of the string.
For every start, we'll find the first valid substring which starts from index start and ends at index end. As this is the first valid substring starting from start but we can also include rest of the character from end index because we already satisfied the minimum criteria of validity. So there would be (N - end) total valid string for this start index.
We'll keep adding all these count into result and finally return the result.
Follow the steps below to implement the above idea:
- Initialize a map for keeping the frequency of characters
- Initialize a variable start = 0, end = 0, and result = 0.
- Do it while the end is less than the size of the given string
- Increment the frequency of character at the end.
- Check if the size of the map becomes K
- Initiate a while loop unless the map size is equal to K.
- Increment the value of the result by N - end, because (N - end) substrings satisfy the given condition
- Decrement the frequency count of characters at the start of the map
- Check if the frequency count of the character at the start of the map becomes 0.
- If true, then remove this character from the map as this character will no longer exist in the valid substring for the new value of start.
- Move the start pointer to right by incrementing its value by 1
- Shift the end pointer to right by incrementing its value by 1.
- Otherwise, Increment the end pointer by 1.
- Return the value of the result
Below is the implementation of the above approach.
C++ // C++ code to implement the approach #include <bits/stdc++.h> using namespace std; // Function to find the number of substrings int numberOfSubstrings(string s, int K) { // Initialize a map for keeping // frequency of characters unordered_map<char, int> unmap; // Initialize a variable start = 0, // end = 0 and result = 0 int start = 0, end = 0, n = s.size(), result = 0; // Do while end is less than size // of given string while (end < n) { // Increment the frequency of // character at end. unmap[s[end]]++; // Check if the size of // map becomes K if (unmap.size() == K) { // Initiate a while loop // unless map size is // equals to K while (unmap.size() == K) { // Increment the value of // result by n - end, because (n - end) // substring are valid that satisfy the // given condition result += n - end; // Decrement the frequency // count of character at // start from map unmap[s[start]]--; // Check if frequency count // of character at start in // map becomes 0. // If true, then remove this // character from the map if (unmap[s[start]] == 0) unmap.erase(s[start]); // Move the start pointer // to right by incrementing // its value by 1 start++; } // Increment the end pointer. end++; } // Otherwise, Increment // the end pointer by 1. else { end++; } } // Return the value of result return result; } // Driver code int main() { string S = "abcabc"; int K = 3; // Function Call cout << numberOfSubstrings(S, K); return 0; }
Java // Java code to implement the approach import java.io.*; import java.util.*; class GFG { // Function to find the number of substrings static int numberOfSubstrings(String s, int K) { // Initialize a map for keeping // frequency of characters HashMap<Character, Integer> unmap = new HashMap<>(); // Initialize a variable start = 0, // end = 0 and result = 0 int start = 0, end = 0, n = s.length(), result = 0; // Do while end is less than size // of given string while (end < n) { // Increment the frequency of // character at end. unmap.put(s.charAt(end), unmap.getOrDefault(s.charAt(end), 0) + 1); // Check if the size of // map becomes K if (unmap.size() == K) { // Initiate a while loop // unless map size is // equals to K while (unmap.size() == K) { // Increment the value of // result by n - end, because (n - end) // substring are valid that satisfy the // given condition result += n - end; // Decrement the frequency // count of character at // start from map unmap.put(s.charAt(start), unmap.get(s.charAt(start)) - 1); // Check if frequency count // of character at start in // map becomes 0. // If true, then remove this // character from the map if (unmap.get(s.charAt(start)) == 0) { unmap.remove(s.charAt(start)); } // Move the start pointer // to right by incrementing // its value by 1 start++; } // Increment the end pointer. end++; } // Otherwise, Increment // the end pointer by 1. else { end++; } } // Return the value of result return result; } public static void main(String[] args) { String S = "abcabc"; int K = 3; // Function call System.out.print(numberOfSubstrings(S, K)); } } // This code is contributed by lokesh
Python3 # Python code to implement the approach # Function to find the number of substrings def numberOfSubstrings(s, K): # Initialize a map for keeping # frequency of characters unmap = {} # Initialize a variable start = 0, # end = 0 and result = 0 start = 0 end = 0 n = len(s) result = 0 # Do while end is less than size # of given string while (end < n): # Increment the frequency of # character at end. unmap[s[end]] = unmap.get(s[end], 0)+1 # Check if the size of # map becomes K if len(unmap) == K: # Initiate a while loop # unless map size is # equals to K while len(unmap) == K: # Increment the value of # result by n - end, because (n - end) # substring are valid that satisfy the # given condition result += n-end # Decrement the frequency # count of character at # start from map unmap[s[start]] -= 1 # Check if frequency count # of character at start in # map becomes 0. # If true, then remove this # character from the map if unmap[s[start]] == 0: unmap.pop(s[start]) # Move the start pointer # to right by incrementing # its value by 1 start += 1 # Increment the end pointer. end += 1 # Otherwise, Increment # the end pointer by 1. else: end += 1 # Return the value of result return result # Driver code S = "abcabc" K = 3 print(numberOfSubstrings(S, K)) # This Code is Contributed By Vivek Maddeshiya
C# // C# code to implement the approach using System; using System.Collections.Generic; public class GFG { // Function to find the number of substrings static int numberOfSubstrings(string s, int K) { // Initialize a map for keeping // frequency of characters Dictionary<char, int> unmap = new Dictionary<char, int>(); // Initialize a variable start = 0, // end = 0 and result = 0 int start = 0, end = 0, n = s.Length, result = 0; // Do while end is less than size // of given string while (end < n) { // Increment the frequency of // character at end. if(unmap.ContainsKey(s[end])){ int temp = unmap[s[end]] + 1; unmap[s[end]] = temp; } else{ unmap[s[end]] = 1; } // Check if the size of // map becomes K if (unmap.Count == K) { // Initiate a while loop // unless map size is // equals to K while (unmap.Count == K) { // Increment the value of // result by n - end, because (n - end) // substring are valid that satisfy the // given condition result += n - end; // Decrement the frequency // count of character at // start from map unmap[s[start]] = unmap[s[start]] - 1; // Check if frequency count // of character at start in // map becomes 0. // If true, then remove this // character from the map if (unmap[s[start]] == 0) { unmap.Remove(s[start]); } // Move the start pointer // to right by incrementing // its value by 1 start++; } // Increment the end pointer. end++; } // Otherwise, Increment // the end pointer by 1. else { end++; } } // Return the value of result return result; } static public void Main() { // Code string S = "abcabc"; int K = 3; // Function call Console.Write(numberOfSubstrings(S, K)); } } // This code is contributed by lokeshmvs21
JavaScript // Javascript code function numberOfSubstrings(s, K) { // Initialize a map for keeping // frequency of characters let unmap = {}; // Initialize a variable start = 0, // end = 0 and result = 0 let start = 0, end = 0, n = s.length, result = 0; // Do while end is less than size // of given string while (end < n) { // Increment the frequency of // character at end. if (unmap[s[end]]) { unmap[s[end]]++; } else { unmap[s[end]] = 1; } // Check if the size of // map becomes K if (Object.keys(unmap).length == K) { // Initiate a while loop // unless map size is // equals to K while (Object.keys(unmap).length == K) { // Increment the value of // result by n - end, because (n - end) // substring are valid that satisfy the // given condition result += n - end; // Decrement the frequency // count of character at // start from map unmap[s[start]]--; // Check if frequency count // of character at start in // map becomes 0. // If true, then remove this // character from the map if (unmap[s[start]] == 0) delete unmap[s[start]]; // Move the start pointer // to right by incrementing // its value by 1 start++; } // Increment the end pointer. end++; } // Otherwise, Increment // the end pointer by 1. else { end++; } } // Return the value of result return result; } // Driver code console.log(numberOfSubstrings("abcabc", 3)); // This code is contributed by ksam24000
Time Complexity: O(N)
Auxiliary Space: O(N)
Another Approach: Using sliding window technique
1)Initialize an array freq of size K to keep track of the frequency of each character in the window. Also, initialize a variable uniqueCount to 0 to keep track of the number of unique characters in the window, and a variable ans to 0 to keep track of the count of valid substrings.
2)Initialize two pointers left and right to 0, which represent the start and end of the current window.
3)While the right pointer is less than the length of the string, do the following:
- Update the frequency of the current character at the right pointer by incrementing the corresponding index in the freq array.
- If the frequency of the current character is 1 (i.e., this character was not previously present in the window), increment the uniqueCount variable.
- Check if uniqueCount is equal to K. If it is, it means that the current window contains all K characters, so we can count the number of valid substrings that can be formed using the current window ending at the right pointer. This count is equal to the length of the substring from the right pointer to the end of the string, which is s.size() - right.
- Slide the window to the right by incrementing the right pointer.
- If uniqueCount is not equal to K, continue sliding the window to the right until it does.
4)When the loop in step 3 ends, return the ans variable, which contains the count of valid substrings.
Below is the implementation of the above approach.
C++ // C++ code to implement the approach #include <bits/stdc++.h> using namespace std; // Function to find the number of substrings int numberOfSubstrings(string s, int K) { int freq[K] = { 0 }; // array to keep track of frequency // of characters in window int uniqueCount = 0; // variable to keep track of unique // characters in window int ans = 0; // variable to keep track of count of valid // substrings int left = 0, right = 0; // pointers for sliding window while (right < s.size()) { // update frequency of current character and unique // count freq[s[right] - 'a']++; if (freq[s[right] - 'a'] == 1) { uniqueCount++; } // if all K characters are present in window while (uniqueCount == K) { ans += (s.size() - right); // count of substrings with // current window ending at // right pointer // update frequency and unique count for // leftmost character in window freq[s[left] - 'a']--; if (freq[s[left] - 'a'] == 0) { uniqueCount--; } left++; // move left pointer to slide window } right++; // move right pointer to slide window } return ans; } // Driver code int main() { string S = "abcabc"; int K = 3; // Function Call cout << numberOfSubstrings(S, K); return 0; }
Java import java.util.HashMap; public class Main { // Function to find the number of substrings public static int numberOfSubstrings(String s, int K) { // array to keep track of frequency // of characters in window int[] freq = new int[K]; // variable to keep track of unique // characters in window int uniqueCount = 0; // variable to keep track of count of valid // substrings int ans = 0; // pointers for sliding window int left = 0, right = 0; while (right < s.length()) { // update frequency of current character and unique // count freq[s.charAt(right) - 'a']++; if (freq[s.charAt(right) - 'a'] == 1) { uniqueCount++; } // if all K characters are present in window while (uniqueCount == K) { ans += (s.length() - right); // count of substrings with // current window ending at // right pointer // update frequency and unique count for // leftmost character in window freq[s.charAt(left) - 'a']--; if (freq[s.charAt(left) - 'a'] == 0) { uniqueCount--; } // move left pointer to slide window left++; } // move right pointer to slide window right++; } return ans; } // Driver code public static void main(String[] args) { String S = "abcabc"; int K = 3; System.out.println(numberOfSubstrings(S, K)); } }
Python3 # code def numberOfSubstrings(s, K): freq = [0]*K # list to keep track of frequency # of characters in window uniqueCount = 0 # variable to keep track of unique # characters in window ans = 0 # variable to keep track of count of valid # substrings left = 0 right = 0 # pointers for sliding window while right < len(s): # update frequency of current character and unique # count freq[ord(s[right]) - ord('a')] += 1 if freq[ord(s[right]) - ord('a')] == 1: uniqueCount += 1 # if all K characters are present in window while uniqueCount == K: ans += len(s) - right # count of substrings with # current window ending at # right pointer # update frequency and unique count for # leftmost character in window freq[ord(s[left]) - ord('a')] -= 1 if freq[ord(s[left]) - ord('a')] == 0: uniqueCount -= 1 left += 1 # move left pointer to slide window right += 1 # move right pointer to slide window return ans # Driver code S = "abcabc" K = 3 # Function Call print(numberOfSubstrings(S, K))
C# // C# code to implement the approach using System; class Program { // Function to find the number of substrings static int numberOfSubstrings(string s, int K) { int[] freq = new int[K]; // array to keep track of // frequency of characters // in window int uniqueCount = 0; // variable to keep track of // unique characters in window int ans = 0; // variable to keep track of count of // valid substrings int left = 0, right = 0; // pointers for sliding window while (right < s.Length) { // update frequency of current character and // unique count freq[s[right] - 'a']++; if (freq[s[right] - 'a'] == 1) { uniqueCount++; } // if all K characters are present in window while (uniqueCount == K) { ans += (s.Length - right); // count of substrings // with current window // ending at right pointer // update frequency and unique count for // leftmost character in window freq[s[left] - 'a']--; if (freq[s[left] - 'a'] == 0) { uniqueCount--; } left++; // move left pointer to slide window } right++; // move right pointer to slide window } return ans; } // Driver code static void Main() { string S = "abcabc"; int K = 3; // Function Call Console.WriteLine(numberOfSubstrings(S, K)); } } // This code is contributed by user_dtewbxkn77n
JavaScript // JS code to implement the approach // Function to find the number of substrings function numberOfSubstrings(s, K) { const freq = new Array(K).fill(0); // array to keep track of frequency // of characters in window let uniqueCount = 0; // variable to keep track of unique // characters in window let ans = 0; // variable to keep track of count of valid // substrings let left = 0, right = 0; // pointers for sliding window while (right < s.length) { // update frequency of current character and unique // count freq[s[right].charCodeAt(0) - 97]++; if (freq[s[right].charCodeAt(0) - 97] == 1) { uniqueCount++; } // if all K characters are present in window while (uniqueCount == K) { ans += (s.length - right); // count of substrings with // current window ending at // right pointer // update frequency and unique count for // leftmost character in window freq[s[left].charCodeAt(0) - 97]--; if (freq[s[left].charCodeAt(0) - 97] == 0) { uniqueCount--; } left++; // move left pointer to slide window } right++; // move right pointer to slide window } return ans; } // Driver code const S = "abcabc"; const K = 3; // Function Call console.log(numberOfSubstrings(S, K));
Time Complexity: O(N)
Auxiliary Space: O(K)
Similar Reads
Find the count of substrings in alphabetic order Given a string of length N consisting of lowercase alphabets. The task is to find the number of such substrings whose characters occur in alphabetical order. Minimum allowed length of substring is 2. Examples: Input : str = "refjhlmnbv" Output : 2 Substrings are: "ef", "mn" Input : str = "qwertyuiop
4 min read
Recursive solution to count substrings with same first and last characters We are given a string S, we need to find count of all contiguous substrings starting and ending with same character. Examples : Input : S = "abcab" Output : 7 There are 15 substrings of "abcab" a, ab, abc, abca, abcab, b, bc, bca bcab, c, ca, cab, a, ab, b Out of the above substrings, there are 7 su
11 min read
Count substrings with same first and last characters Given a string s consisting of lowercase characters, the task is to find the count of all substrings that start and end with the same character.Examples : Input : s = "abcab"Output : 7Explanation: The substrings are "a", "abca", "b", "bcab", "c", "a", "b".Input : s = "aba"Output : 4Explanation: The
7 min read
Count occurrences of a sub-string with one variable character Given two strings a and b, and an integer k which is the index in b at which the character can be changed to any other character, the task is to check if b is a sub-string in a and print out how many times b occurs in a in total after replacing the b[k] with every possible lowercase character of Eng
5 min read
Count of palindromic strings of size upto N consisting of first K alphabets occurring at most twice Given two integers N and K, the task is to find the number of palindromic strings of size at most N consisting of the first K lowercase alphabets such that each character in a string doesn't appear more than twice. Examples: Input: N = 3, K = 2Output: 6Explanation:The possible strings are:"a", "b",
9 min read