VOOZH about

URL: https://www.geeksforgeeks.org/dsa/given-number-find-number-contiguous-subsequences-recursively-add-9/

⇱ Given a number as a string, find the number of contiguous subsequences which recursively add up to 9 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Given a number as a string, find the number of contiguous subsequences which recursively add up to 9

Last Updated : 23 Jul, 2025

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.

Example: 

Digits of 729 recursively add to 9, 
7 + 2 + 9 = 18 
Recur for 18 
1 + 8 = 9

Examples: 

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. 


Output
3
5

Time complexity of the above program is O(n2). Please let me know if there is a better solution.

Auxiliary Space :O(1), since no extra space is used.
Given a number as a string, find the number of contiguous subsequences which recursively add up to 9 | Set 2 

Comment
Article Tags: