Given a number as a string, write a function to find the number of substrings (or contiguous subsequences) of the given string which recursively add up to 9.
For example digits of 729 recursively add to 9,
7 + 2 + 9 = 18
Recur for 18
1 + 8 = 9
Input: 4189 Output: 3 There are three substrings which recursively add to 9. The substrings are 18, 9 and 189. Input: 999 Output: 6 There are 6 substrings which recursively add to 9. 9, 99, 999, 9, 99, 9
All digits of a number recursively add up to 9, if only if the number is multiple of 9. We basically need to check for s%9 for all substrings s. One trick used in below program is to do modular arithmetic to avoid overflow for big strings.
Following is a simple implementation based on this approach. The implementation assumes that there are no leading 0’s in input number.
Time complexity of the above program is O(n2). Please let me know if there is a better solution.
This article is contributed by Abhishek. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
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.
- Given a number as a string, find the number of contiguous subsequences which recursively add up to 9 | Set 2
- Check if a string can become empty by recursively deleting a given sub-string
- Count the number of contiguous increasing and decreasing subsequences in a sequence
- Count subsequences in first string which are anagrams of the second string
- Decode a string recursively encoded as count followed by substring
- Print all Subsequences of String which Start with Vowel and End with Consonant.
- Find product of all elements at indexes which are factors of M for all possible sorted subsequences of length M
- Recursively print all sentences that can be formed from list of word lists
- Count occurrences of a substring recursively
- Recursively remove all adjacent duplicates
- Construct a string that has exactly K subsequences from given string
- Count of subsequences which consists exactly K prime numbers
- Count subsequences which contains both the maximum and minimum array element
- Count subsequences for every array element in which they are the maximum
- Number of subsequences in a given binary string divisible by 2
- Check if a string can be obtained by appending subsequences of another string
- Check if string S2 can be obtained by appending subsequences of string S1
- Maximum contiguous 1 possible in a binary string after k rotations
- Distinct state codes that appear in a string as contiguous sub-strings
- Contiguous subsegments of a string having distinct subsequent characters