VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-number-of-substrings-with-numeric-value-greater-than-x/

⇱ Count number of substrings with numeric value greater than X - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count number of substrings with numeric value greater than X

Last Updated : 17 Apr, 2023

Given a string 'S' (composed of digits) and an integer 'X", the task is to count all the sub-strings of 'S' that satisfy the following conditions:  

  • The sub-string must not begin with the digit '0'.
  • And the numeric number it represents must be greater than 'X'.

Note: Two ways of selecting a sub-string are different if they begin or end at different indices.

Examples:  

Input: S = "471", X = 47
Output: 2
Only the sub-strings "471" and "71" 
satisfy the given conditions.

Input: S = "2222", X = 97
Output: 3
Valid strings are "222", "222" and "2222". 

Approach:  

  • Iterate over each digit of the string 'S' and choose the digits which are greater than '0'.
  • Now, take all possible sub-strings starting from the character chosen in the previous step and convert each sub-string to an integer.
  • Compare the integer from the previous step to 'X'. If the number is greater than 'X', then increment the count variable.
  • Finally, print the value of the count variable.

Below is the implementation of the above approach:  


Output
3

Complexity Analysis:

  • Time Complexity: O(N3)
  • Auxiliary Space: O(1)
Comment
Article Tags:
Article Tags: