Problem 668 · LeetCode 668(opens in a new tab)
Kth Smallest Number in Multiplication Table
HardBinary search
Picture a multiplication table with m rows and n columns, numbered from 1. The cell in row r and column c holds r × c.
Sort every cell of that table from small to large, keeping repeated values as separate entries. Return the value at position k of that order (position 1 is the smallest).
Example 1
Input: m = 3, n = 4, k = 8 Output: 6 Why: sorted: 1, 2, 2, 3, 3, 4, 4, 6, …
2 more examples and the constraints
Example 2
Input: m = 2, n = 5, k = 7 Output: 5 Why: sorted: 1, 2, 2, 3, 4, 4, 5, 6, 8, 10
Example 3
Input: m = 4, n = 4, k = 16 Output: 16 Why: the last value is the biggest, 4 × 4
Constraints
- 1 ≤ m, n ≤ 30,000
- 1 ≤ k ≤ m × n
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- List and sortO(mn log(mn))
- Binary search on the valueO(m log(mn))
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 1,000 × 1,000 table | Verdict |
|---|---|---|---|
| List and sort | O(mn log(mn)) | Fine for tiny tables, huge memory | |
| Binary search on the value | O(m log(mn)) | Best; never builds the table |
m = rows, n = columns.
Edge cases to test
- A 1 × 1 table. m = n = 1, k = 1 gives 1.
- k = m × n. The largest value, m × n itself.
- k = 1. Always 1, the top-left cell.
- One row or one column. The table is 1, 2, …, n, so the answer is k.
- Repeated values. Many cells share a value; counting ≤ mid handles ties, while counting < mid would not.
Common mistakes
- Counting
mid // rwithout capping it at n, so a row is credited more cells than it has. - Returning mid when the count equals k, which may be a value not in the table.
- Using
hi = mid - 1on a hit, which can skip the answer.
How to talk through it
- 1Clarify. Do repeated values count separately? Are rows and columns numbered from 1?
- 2Give the brute force. List all m·n products and sort: correct, but 900 million cells at the limit.
- 3Flip the question. Counting cells ≤ x is easy row by row: min(x // r, n).
- 4Binary search the value. Find the smallest x with count ≥ k; it is always in the table.
- 5Test out loud. Run m = 3, n = 4, k = 8 and the k = m × n case.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?