Ctrl K

Numbers in Dictionary Order

Medium
All integers from 1 to limit are written out as words and arranged as in a dictionary: digits are compared from left to right, and if one number is a prefix of another, the shorter one comes first. For example, 12 comes before 2, and 1 comes before 10. Return the numbers from 1 to limit in that order. Try to do it in O(limit) time with O(1) extra space besides the answer.
Example 1
limit=21 → [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 3, 4, 5, 6, 7, 8, 9]

Like in a dictionary: 1 first, then everything starting with 1 (10–19), then 2, 20, 21, and finally 3–9.

Example 2
limit=5 → [1, 2, 3, 4, 5]

All numbers have one digit, so the order is the usual one.

Example 3
limit=100 → [1, 10, 100, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 4, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 5, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 6, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 7, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 8, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 9, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
Constraints
  • 1 ≤ limit ≤ 5·10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsOutermost Folders Only MediumEvery Start Is a Word MediumWords Built From Shorter Words HardBest XOR Up the Chain of Command HardXOR of Two Disjoint Subtrees Hard
loading Python…
Input
limit=21
Expected
[1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 3, 4, 5, 6, 7, 8, 9]

Run checks the first 3 tests in your browser. Submit checks all 40 tests on the server, hidden ones included.