![]() |
VOOZH | about |
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: 3Input: 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:
Below is the implementation of the algorithm:
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.