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
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!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code