Skip to content
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.

Try it on LeetCode(opens in a new tab)
  1. List and sortO(mn log(mn))
  2. 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

ApproachTimeRelative work for a 1,000 × 1,000 tableVerdict
List and sortO(mn log(mn))
Fine for tiny tables, huge memory
Binary search on the valueO(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 // r without 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 - 1 on a hit, which can skip the answer.

How to talk through it

  1. 1Clarify. Do repeated values count separately? Are rows and columns numbered from 1?
  2. 2Give the brute force. List all m·n products and sort: correct, but 900 million cells at the limit.
  3. 3Flip the question. Counting cells ≤ x is easy row by row: min(x // r, n).
  4. 4Binary search the value. Find the smallest x with count ≥ k; it is always in the table.
  5. 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?