Kth Smallest Number in Multiplication Table - Problem

Imagine you're looking at a multiplication table that every student learns in elementary school, but this time it's arranged as a matrix! 📊

Given three integers m, n, and k, you need to find the k-th smallest element in an m × n multiplication table where mat[i][j] = i * j (using 1-based indexing).

For example, a 3×3 multiplication table looks like:

[1, 2, 3]
[2, 4, 6]
[3, 6, 9]

Your task is to find the k-th smallest number when all elements are considered in sorted order: 1, 2, 2, 3, 3, 4, 6, 6, 9

The challenge: Can you do this without actually generating the entire table? 🤔

Input & Output

example_1.py — Small Table
$ Input: m = 3, n = 3, k = 5
Output: 3
💡 Note: The 3×3 multiplication table is [[1,2,3],[2,4,6],[3,6,9]]. When flattened and sorted: [1,2,2,3,3,4,6,6,9]. The 5th smallest element is 3.
example_2.py — Rectangular Table
$ Input: m = 2, n = 3, k = 6
Output: 6
💡 Note: The 2×3 multiplication table is [[1,2,3],[2,4,6]]. When flattened and sorted: [1,2,2,3,4,6]. The 6th (last) smallest element is 6.
example_3.py — Large K
$ Input: m = 4, n = 4, k = 10
Output: 6
💡 Note: In a 4×4 table, sorted values are [1,2,2,3,3,3,4,4,4,6,6,6,8,8,9,12,16]. The 10th smallest is 6.

Constraints

  • 1 ≤ m, n ≤ 3 × 104
  • 1 ≤ k ≤ m × n
  • Memory constraint: Cannot store all m×n values for large inputs

Visualization

Tap to expand
Binary Search on Multiplication TableStep 1: Multiplication Table (3×3)1×1=11×2=21×3=32×1=22×2=42×3=63×1=33×2=63×3=9Step 2: Binary Search Process19Guess: mid = 5Count elements ≤ 5:Row 1: min(5÷1, 3) = min(5, 3) = 3Row 2: min(5÷2, 3) = min(2, 3) = 2Row 3: min(5÷3, 3) = min(1, 3) = 1Total: 3+2+1 = 6Step 3: DecisionCount = 6 ≥ k = 5 ✓Answer ≤ 5Search left: [1, 5]Continue until left == rightFinal Answer: 3Why This Works: Sorted Values VisualizationOriginal: [1,2,3,2,4,6,3,6,9] → Sorted: [1,2,2,3,3,4,6,6,9]122334669k=5th element
Understanding the Visualization
1
Set Search Range
Initialize binary search between 1 and m×n (smallest and largest possible values)
2
Make a Guess
Pick the middle value and count how many table elements are ≤ this guess
3
Smart Counting
For each row i, count min(guess/i, n) elements that are ≤ guess
4
Adjust Range
If count ≥ k, answer could be this or smaller. If count < k, answer is larger
5
Converge
Repeat until we find the exact k-th smallest value
Key Takeaway
🎯 Key Insight: Instead of generating O(mn) values, we binary search on the answer and count elements ≤ our guess in O(m) time, achieving optimal O(m log(mn)) complexity!
Asked in
Google 45 Microsoft 38 Amazon 32 Meta 28
52.0K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen