Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

The k-th smallest entry of a multiplication table

Hard · Target 25 minutes · Binary search · Type asked atGoogleHudson River TradingOptiver

The m × n multiplication table has the value i × j in row i and column j (both counted from 1). Return the k-th smallest value in the table, counting repeats. The table has up to 9 × 10⁸ cells, so it cannot be built.

Examples

InputOutputWhy
m = 3, n = 3, k = 53Values in order: 1, 2, 2, 3, 3, 4, 6, 6, 9.
m = 2, n = 3, k = 66

Constraints

  • 1 ≤ m, n ≤ 3 × 10⁴
  • 1 ≤ k ≤ m × n

Hints

Hint 1

Building and sorting the table is out of the question. What can you compute quickly for a given value x?

Hint 2

Row i is i, 2i, 3i, …, n·i. How many of those are ≤ x?

Hint 3

min(⌊x / i⌋, n). Sum over the rows to get count(x) in O(m), then find the smallest x with count(x) ≥ k.

Where people lose marks

  • Forgetting the cap at n: row 1 has n entries, not x of them.
  • Returning the first x whose count equals k: with repeats the count can jump past k without equalling it.
  • Computing m × n in 32 bits: up to 9 × 10⁸ fits, but only just; use 64 bits for the bound and the count.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.