K-th Smallest in Lexicographical Order

Intuition

Flow

Small example → tle dfs → optimized dfs by jumping over calls.

Code

class Solution:
    def findKthNumber(self, n: int, k: int) -> int:
        curr, k = 1, k - 1  # note k - 1
        
        def countSteps(n, prefix1, prefix2):
            steps = 0
            while prefix1 <= n:
                # get steps at this level
                # n + 1 for inclusivity
                steps += min(n + 1, prefix2) - prefix1  
                # move to next level of the tree
                prefix1 *= 10
                prefix2 *= 10
            return steps
        
        while k > 0:
            steps = countSteps(n, curr, curr + 1)
            # steps between current and following
            if steps <= k:
                curr += 1
                k -= steps
            else:
                curr *= 10
                k -= 1
        
        return curr

Editorial code above.