Kth Smallest Number in Multiplication Table

Binary search the value; count how many cells of the m-by-n multiplication table are at most mid via a per-row division.

Hard
Time O(m log(m*n)) Space O(1)
LeetCode
4 min read
binary-search matrix parametric-search

Problem#

In an m x n multiplication table (cell (i, j) contains i * j, 1-indexed), return the k-th smallest value.

Examples#

  • m = 3, n = 3, k = 53
  • m = 2, n = 3, k = 66

Constraints#

  • 1 <= m, n <= 3 * 10^4, 1 <= k <= m * n.

Approach#

The count of cells with value at most v is sum over i in 1..m of min(v / i, n). This count is monotone in v. Binary search v over [1, m*n]; pick the smallest v whose count is at least k.

Solution#

Kth Smallest Number in Multiplication Table
class Solution {
public:
int findKthNumber(int m, int n, int k) {
auto countLE = [&](int v) {
int total = 0;
for (int i = 1; i <= m; ++i) total += min(v / i, n);
return total;
};
int lo = 1, hi = m * n;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (countLE(mid) < k) lo = mid + 1;
else hi = mid;
}
return lo;
}
};

Editorial#

Row i contains values i, 2i, ..., n*i; the count at or below v is min(v / i, n). Summing across rows gives the rank of v. Binary search finds the smallest v whose rank is at least k — that’s the k-th smallest value.

Complexity#

  • Time: O(m log(m*n)).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.