I need to find the $n$-th number that contains the digit $k$ or is divisible by $k$, where $2 \leqslant k \leqslant 9$.
Example: If $n = 15$ and $k = 3$, then the answer is
$$ 33\quad (3, 6, 9, 12, 13, 15, 18, 21, 23, 24, 27, 30, 31, 32, 33)$$
I started following the sequence but couldn't formulate it:
for multiples of $3 \to 3+3+3+4+3+3+4+3+3+4$
for containing digit $3 \to 1+1+1+10+1+1+1+1+1+1$
I have to answer in better than $\mathcal O(n)$ or in $\mathcal O(1)$ if possible. Please don't suggest methods that checks every number in a for loop. Thanks.
Edit: I have searched everywhere but couldn't find it answered anywhere. So, it's not a duplicate.
Say a number is good if it is a multiple of $k$ or contains the digit $k$ (or both). The key idea is to find a fast way to compute $f(m)$, the number of good numbers $< m$. With such a function $f$ at hand, you can find the desired result, namely one less that the smallest $m$ with $f(m)=n$ by binary search (starting with $n$ as lower bound and $nk$ as upper bound). This requires $\log(nk)$ calls to $f$, so we better find a fast implementation of $f$.
We make use of a helper function: Assume $a$ is a multiple of $10^q$ and does not contain digit $k$. Assume $a\equiv r\pmod k$. Then $f(a+10^q)-f(a)$ depends only on $q$ and $r$, so let's call this value $g(q,r)$. We can precompute and memoize $g$ for all combinatons of $0\le q<\lceil\log_{10}n\rceil$ and $0\le r<k$ as follows:
We have $$g(0,r)=\begin{cases}1&\text{r=0}\\0&\text{otherwise}\end{cases}$$ and $$g(q+1,r)=10^q+\sum_{j=0\atop j\ne k}^9 g\bigl (q,r+(10^qj\bmod k)\bigr ).$$ Using this, we can compute $f(n)$ by adding at most digit-sum of $n$ such values of $g$ (where you have to be careful in the beginning if $n$ itself contains a digit $k$)
The whole computation costs $O(\log(n)^2)$ time and $O(\log(n))$ space.
I think the following might be close to working (provided you have
getG):