Find the k-th smallest integer from 1 to n in lexicographical order

Quick Overview

Given n and k, find the k-th integer in the range 1 to n when the numbers are ordered as decimal strings in dictionary order. Since n can be as large as one billion, it tests reasoning about the structure of that order and counting numbers without listing them.

Find the k-th smallest integer from 1 to n in lexicographical order

Company: ByteDance

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: hard

Interview Round: Other

Given two integers `n` and `k`, return the `k`-th lexicographically smallest integer in the range `[1, n]`. ### Function Signature ```python def find_kth_number(n: int, k: int) -> int: ``` ### Rules - Lexicographic order compares the decimal representations as strings, with no leading zeros. For example, `10` comes before `2`, and `1` comes before `10`. - `k` is 1-indexed: `k = 1` asks for the first number in that order. ### Constraints - `1 <= n <= 10^9` - `1 <= k <= n` ### Examples ```text Input: n = 13, k = 2 Output: 10 ``` The lexicographic order of 1 to 13 is `[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]`, and the 2nd element is 10. ```text Input: n = 1, k = 1 Output: 1 ``` Only one number exists in the range, so the answer is 1. ```text Input: n = 100, k = 15 Output: 21 ``` The numbers that start with the digit 1 come first: 1, 10, 100, 11 to 19, which is 12 numbers. They are followed by 2, 20 and 21, so the 15th number is 21.

Overview: Given n and k, find the k-th integer in the range 1 to n when the numbers are ordered as decimal strings in dictionary order. Since n can be as large as one billion, it tests reasoning about the structure of that order and counting numbers without listing them.

ByteDance logo
ByteDance
Nov 25, 2026
hardSoftware EngineerOtherCoding & Algorithms
0
0

Given two integers n and k, return the k-th lexicographically smallest integer in the range [1, n].

Function Signature

def find_kth_number(n: int, k: int) -> int:

Rules

  • Lexicographic order compares the decimal representations as strings, with no leading zeros. For example, 10 comes before 2 , and 1 comes before 10 .
  • k is 1-indexed: k = 1 asks for the first number in that order.

Constraints

  • 1 <= n <= 10^9
  • 1 <= k <= n

Examples

Input: n = 13, k = 2
Output: 10

The lexicographic order of 1 to 13 is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], and the 2nd element is 10.

Input: n = 1, k = 1
Output: 1

Only one number exists in the range, so the answer is 1.

Input: n = 100, k = 15
Output: 21

The numbers that start with the digit 1 come first: 1, 10, 100, 11 to 19, which is 12 numbers. They are followed by 2, 20 and 21, so the 15th number is 21.