Given a string S consisting of small English letters and a string W consisting of weight of all characters of English alphabet where for all i, . We have to find the total numbers of a unique substring with sum of weights at most K.
Input : P = “ababab”, Q = “12345678912345678912345678”, K=5
Output : 7
The unique substrings are: “a”, “ab”, “b”, “bc”, “c”, “d”, “e”
Hence, the count is 7.
Input : P = “acbacbacaa”, Q = “12300045600078900012345000”, K=2
Output : 3
Explanation :The unique substrings are: “a”, “b”, “aa”
Hence, the count is 3.
To solve the above problem, the main idea is to simply iterate through all the substrings and maintain a sum of the weight of all characters encountered so far. If the sum of characters is not greater than K, then insert it in a hashmap otherwise discard it and move forward with another substring. Finally, the result will be the size of the hashmap because it stores all the substring which have weight less than or equal to K.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Count substrings with each character occurring at most k times
- Count distinct substrings that contain some characters at most k times
- Count ways to split a Binary String into three substrings having equal count of zeros
- Count the number of vowels occurring in all the substrings of given string
- Count all Prime Length Palindromic Substrings
- Count substrings that contain all vowels | SET 2
- Count all substrings having character K
- Count of all unique substrings with non-repeating characters
- Count of substrings having all distinct characters
- Count of substrings of a given Binary string with all characters same
- Check if all substrings of length K of a Binary String has equal count of 0s and 1s
- Count of Substrings having Sum equal to their Length
- Sum of all substrings of a string representing a number | Set 1
- Sum of all substrings of a string representing a number | Set 2 (Constant Extra Space)
- Count of binary strings of length N with even set bit count and at most K consecutive 1s
- Given a binary string, count number of substrings that start and end with 1.
- Count number of substrings with exactly k distinct characters
- Count Substrings with equal number of 0s, 1s and 2s
- Count of distinct substrings of a string using Suffix Trie
- Count of distinct substrings of a string using Suffix Array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.