Kth Smallest Number in Multiplication Table - Problem

Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j (1-indexed).

Given three integers m, n, and k, return the k-th smallest element in the m x n multiplication table.

Example:

  • For m = 3, n = 3, k = 5, the multiplication table is:
1  2  3
2  4  6
3  6  9

The sorted elements are: [1, 2, 2, 3, 3, 4, 6, 6, 9], so the 5th smallest is 3.

Input & Output

Example 1 — Basic Case
$ 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]]. Sorted values: [1,2,2,3,3,4,6,6,9]. The 5th smallest is 3.
Example 2 — First Element
$ Input: m = 2, n = 3, k = 1
Output: 1
💡 Note: The 2×3 table is [[1,2,3],[2,4,6]]. Sorted: [1,2,2,3,4,6]. The 1st smallest is 1.
Example 3 — Last Element
$ Input: m = 2, n = 2, k = 4
Output: 4
💡 Note: The 2×2 table is [[1,2],[2,4]]. Sorted: [1,2,2,4]. The 4th smallest is 4.

Constraints

  • 1 ≤ m, n ≤ 3 * 104
  • 1 ≤ k ≤ m * n

Visualization

Tap to expand
Kth Smallest in Multiplication Table INPUT 3 x 3 Multiplication Table x 1 2 3 1 1 2 3 2 2 4 6 3 3 6 9 Sorted: 1, 2, 2, 3, 3, 4, 6, 6, 9 m = 3 n = 3 k = 5 Find 5th smallest element Range: [1, 9] Highlighted: value 3 appears twice ALGORITHM STEPS 1 Binary Search Setup lo = 1, hi = m * n = 9 2 Calculate Mid mid = (lo + hi) / 2 3 Count Elements Count nums <= mid in table 4 Narrow Search If count < k: lo = mid + 1 Else: hi = mid Binary Search Trace: lo=1, hi=9, mid=5 count(5)=6 >= 5 --> hi=5 lo=1, hi=5, mid=3 count(3)=5 >= 5 --> hi=3 lo=1, hi=3, mid=2 count(2)=4 < 5 --> lo=3 FINAL RESULT When lo == hi, answer found! Output: 3 OK - Verified! Sorted elements: 1 2 2 3 3 4 ... 5th element (k=5) is 3 Complexity: Time: O(m * log(m*n)) Space: O(1) Key Insight: Binary search on VALUE, not INDEX! For each mid value, count how many elements in the table are <= mid. For row i, there are min(mid/i, n) such elements. If count < k, search higher; otherwise search lower. This avoids O(m*n) sorting and achieves O(m * log(m*n)) time. TutorialsPoint - Kth Smallest Number in Multiplication Table | Binary Search Approach
Asked in
Google 25 Amazon 20 Facebook 15
28.0K Views
Medium Frequency
~25 min Avg. Time
856 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