Skip to content
Problem 440 · LeetCode 440(opens in a new tab)

K-th Smallest in Lexicographical Order

HardMath

Take the whole numbers from 1 to n and sort them as if they were words, comparing digit by digit from the left: 1 comes before 10, which comes before 2. In this dictionary order, 1 to 12 reads 1, 10, 11, 12, 2, 3, ..., 9.

Return the number that sits in position k of that order, counting from 1.

Example 1

Input:  n = 22, k = 14
Output: 21
Why:    the order starts 1, 10, ..., 19, 2, 20, 21
2 more examples and the constraints

Example 2

Input:  n = 100, k = 3
Output: 100
Why:    the order starts 1, 10, 100, 11

Example 3

Input:  n = 5, k = 5
Output: 5
Why:    with one-digit numbers the order is just 1 to 5

Constraints

  • 1 ≤ k ≤ n ≤ 1,000,000,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Walk one number at a timeO(k)
  2. Skip whole subtreesO(log² n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for k = 1,000,000,000Verdict
Walk one number at a timeO(k)
Too slow for large k
Skip whole subtreesO(log² n)
Best; a few hundred steps

n = largest number, k = position asked for.

Edge cases to test

  • k = 1. The answer is always 1; the loop does not run.
  • n below 10. The order is plain counting, so the answer is k.
  • A cut-off subtree. With n = 100, the prefix 1 holds 1, 10 to 19 and only 100 from the next level: 12 numbers, not 111.
  • n near a billion. The count's upper bound grows past 32 bits; keep it in 64-bit.

Common mistakes

  • Counting a full subtree of 1, 10, 100 ... numbers without cutting each level at n.
  • Forgetting to subtract 1 when stepping down, since the prefix itself is one of the numbers.
  • Computing hi * 10 + 9 in 32-bit integers, which overflows for n near 10^9.

How to talk through it

  1. 1Clarify. Is k counted from 1? How large can n and k be? Is the order digit by digit, like strings?
  2. 2See the tree. Dictionary order is a preorder walk of a 10-ary prefix tree.
  3. 3Give the walk. Step to the next number k − 1 times: O(k), too slow for a billion.
  4. 4Skip subtrees. Count a prefix's numbers level by level; skip it if the count fits in what is left, else step down.
  5. 5Test out loud. Walk n = 22, k = 14 and n = 100, k = 3, then mention k = 1.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?