VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-of-strobogrammatic-number-in-range-l-r-strobogrammatic-number-iii/

⇱ Number of Strobogrammatic Number in Range [l, r] (Strobogrammatic Number III) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number of Strobogrammatic Number in Range [l, r] (Strobogrammatic Number III)

Last Updated : 14 Jun, 2024

Given two strings l and r, which represent two integers l and r where l <= r. The task is to return the number of strobogrammatic numbers in the range [l, r]. A strobogrammatic number is a number that looks the same when rotated 180 degrees (i.e., when viewed upside down).

Example:

Input: l = "50", r = "100"
Output: 3

Input: l = "0", r = "0"
Output: 1

Approach:

For any number string s, the strobogrammatic number can only be

8 + s[1:-1] + 8, 1 + s[1:-1] + 1, 0 + s[1:-1] + 0, 6 + s[1:-1] + 9, 9 + s[1:-1] + 6.

It's easy to get that for any digit i, the number of the strobogrammatic string on that digit is dp[i] = dp[i - 2] * 5

As the constraint gives that the highest digit is 15, so at most we can get 3* (5 ** 7) = 234375 numbers with the given highest constraint, which is still possible to generate all of them.

Step-by-step algorithm:

  • Use dp to generate all of the strobogrammatic strings,
  • Convert them to number and add to a SortedSet()
  • For this step, be careful the numbers strings that start with "0",
  • All of those should be removed except the real "0"
  • Use binary search to find the left and right index with given l and r

Below is the implementation of the algorithm:


Output
3

Time complexity: O(n log n), where n is the length of the r string. This is because the code generates all strobogrammatic numbers of lengths from 0 to n, which takes O(n) time, and then sorts these numbers, which takes O(n log n) time.
Auxiliary space: O(n). This is because the code uses a map to store the strobogrammatic numbers of different lengths, and the total number of these numbers is proportional to the length of the r string.


Comment