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:
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Count all substrings having character K
- Count substrings with same first and last characters
- Count substrings that contain all vowels | SET 2
- Count of substrings of a binary string containing K ones
- Count of substrings formed using a given set of characters only
- Number of substrings with count of each character as k
- Count of substrings consisting only of vowels
- Count Substrings with equal number of 0s, 1s and 2s
- Count of substrings which contains a given character K times
- Count of total anagram substrings
- Count all Prime Length Palindromic Substrings
- Count of all unique substrings with non-repeating characters
- Count number of distinct substrings of a given length
- Find the count of substrings in alphabetic order
- Recursive solution to count substrings with same first and last characters
- Count number of substrings with exactly k distinct characters
- Count number of substrings with numeric value greater than X
- Count of Palindromic substrings in an Index range
- Count of Substrings that can be formed without using the given list of Characters
- Count substrings with each character occurring at most k times
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.
Improved By : SURENDRA_GANGWAR