![]() |
VOOZH | about |
Given an integer n (1 <= n <= 1010), count the number of valid numbers in the range [1, n] (inclusive).
Note: A number is called valid if digits 2, 4, and 8 occur in it with equal nonzero frequencies. For example, numbers 248, 284824, and 2148 are valid, whereas numbers 3456 (different frequencies) and 356 (zero frequencies) are not.
Examples:
Input: n = 300
Output: 2
Explanation: 248 and 284 are the only valid integers in range.Input: n = 1248
Output: 7
Explanation: 248, 284, 428, 482, 824, 842, 1248 are the valid integers in range.
Approach: To solve the problem follow the below idea:
Use digit DP to count the numbers in the range [0, n] where the count of digits 2, 4, and 8 are all equal and greater than zero.
Follow the steps to solve the problem:
Below is the C++ implementation of the above approach:
7
Time Complexity: O(10^(log10(n))), number of recursive calls for string s of n length, which is O(log10(n)), at each level of recursion loop runs 10 times.
Auxiliary Space: O(n), as we are using 4D dp array.