Amusing Numbers
Statement
Consider the integers from 1 to N, ordered lexicographically — the way a dictionary would order them as strings — rather than numerically. For N = 11 the order is 1, 10, 11, 2, 3, 4, 5, 6, 7, 8, 9. Let Q(N, K) be the 1-based position of the number K in this ordering; for N = 11, Q(11, 2) = 4.
Given K and M, find the smallest N such that Q(N, K) = M.
Input / Output
Input: two integers K and M (1 ≤ K, M ≤ 10⁹) separated by a space.
Output: the smallest N with Q(N, K) = M, or 0 if no such N exists.
Constraints
- 1 ≤ K, M ≤ 10⁹
- The answer N can be far larger than 10⁹ (up to roughly 18 digits), so it does not fit in a 32-bit or even a naive 64-bit running total without care.
Example
Input: 2 4
Output: 11
Input: 2 1
Output: 0
Input: 100000001 1000000000
Output: 100000000888888879
Input: 1000000000 11
Output: 0
Solution idea
Fix the number of digits i that N will have and count, for that many
digits, how many numbers of length ≤ i sort lexicographically before K —
call that count C. As i grows this prefix-count only increases, so the
right i is the first one where the running count reaches M. Within that
digit length, the lexicographic rank of K is determined by "how many i-digit
strings are less than K's own padded value," which reduces to a digit-DP
style walk over K's decimal digits.
Concretely: for each digit length i, build the largest i-digit number
that is still lexicographically before K (this is K's decimal representation
truncated/adjusted to i digits, with its last kept digit decremented), and
add that count to a running total. Once the running total reaches or passes
M at digit length i, the answer's own decimal digits can be reconstructed
directly from M - C by walking back through the same counting logic and
appending digit i on top of K. Because N can have up to ~19 digits, all of
this arithmetic (add, subtract, compare) is done on custom big integers
represented as digit arrays rather than machine integers.





