Given a number n, write a function that returns count of numbers from 1 to n that don’t contain digit 3 in their decimal representation
What can be the most optimal way of solving this problem.
the approach i am using in naive i.e nlogn (easy to guess the approach by seeing complexity 🙂 )
The following algorithm computes the number of integers from 0 to (n-1) without “3” in their decimal representation quite efficiently. (I have modified the interval from 1 .. n to 0 .. n-1 only to simplify the following calculations slightly.)
(I am not an expert in complexity calculations, but I think the complexity of this algorithm is
O(log n), because it does a fixed number of steps for each digit ofn.)The first observation is that the number of integers with at most d digits (i.e. the numbers in the interval 0 .. 10d-1) not having the digit 3 in their decimal representation is exactly 9d, because for each digit you have 9 possible choices 0,1,2,4,5,6,7,8,9.
Now let me demonstrate the algorithm with a 5 digit number n = a4a3a2a1a0.
We compute separately the number of integers with no “3” in their decimal representation for the intervals
The number of integers in the interval Ij that do not have a “3” in the decimal representation is
otherwise:
jth digit, 9 choices for all lower valued digits),
So we have the following function: