Magicsheet logo

Kth Smallest Number in Multiplication Table

Hard
39.6%
Updated 6/1/2025

Kth Smallest Number in Multiplication Table

1. What is this problem about?

The Kth Smallest Number in Multiplication Table interview question asks you to find the kthk^{th} smallest integer in an mimesnm imes n table where table[i][j] = i * j. The values in the table are between 11 and mimesnm imes n. Because the table can be 30,000imes30,00030,000 imes 30,000, you cannot build or sort it.

2. Why is this asked in interviews?

Companies like Google and Uber ask this to test your ability to perform Binary Search on the answer space. It tests whether you can use a mathematical shortcut to count how many numbers are less than XX in a multiplication table in O(M)O(M) time. It evaluation your Binary Search interview pattern proficiency.

3. Algorithmic pattern used

This follows the Binary Search on Value pattern.

  1. Range: The answer is between 1 and mimesnm imes n.
  2. Counting Function: For a given value XX, how many numbers in the table are X\leq X?
    • In row ii, the numbers are i,2i,3i,,nii, 2i, 3i, \dots, ni.
    • The number of elements X\leq X in row ii is min(X / i, n).
    • Total count is sum(min(X / i, n)) for all ii from 1 to mm.
  3. Binary Search: Use this function to find the smallest XX such that count(X) >= k.

4. Example explanation

m=3,n=3,k=5m=3, n=3, k=5. Table:

1 2 3
2 4 6
3 6 9

Sorted: 1, 2, 2, 3, 3, 4, 6, 6, 9. k=5k=5 is 3.

  • Range [1, 9]. Try mid = 4.
  • Count 4\leq 4:
    • row 1: min(4/1, 3) = 3.
    • row 2: min(4/2, 3) = 2.
    • row 3: min(4/3, 3) = 1.
  • Total = 6. Since 656 \geq 5, 4 is a candidate. Try smaller.

5. Common mistakes candidates make

  • Linear approach: Trying to iterate through the table (O(MN)O(M \cdot N)).
  • Off-by-one: Mistakes in the binary search boundaries or the count(X) >= k logic.
  • Integer overflow: Forgetting that mimesnm imes n can exceed 23112^{31}-1.

6. Interview preparation tip

Binary Search on the answer is the secret to almost all "Kth something in a virtual matrix" problems. Whenever you can't build the dataset, check if you can easily "count elements less than XX."

Similar Questions