
Sponsored
Sponsored
The general idea is to use binary search to find the kth smallest element in the multiplication table. The key observation is that for a candidate number X, we can count how many numbers in the multiplication table are less than or equal to X, without constructing the entire table explicitly. Counting these numbers can be efficiently done by iterating over the rows and determining the highest multiple that does not exceed X.
Time Complexity: O(m * log(m * n))
Space Complexity: O(1)
1function countLessOrEqual(m, n, x) {
2 let count = 0;
3 for (let i = 1; i <= m; i++) {
4 count += Math.min(Math.floor(x / i), n);
5 }
6 return count;
7}
8
9function findKthNumber(m, n, k) {
10 let low = 1, high = m * n;
11 while (low < high) {
12 const mid = Math.floor((low + high) / 2);
13 if (countLessOrEqual(m, n, mid) < k)
14 low = mid + 1;
15 else
16 high = mid;
17 }
18 return low;
19}
20
21console.log(findKthNumber(3, 3, 5)); // Output: 3This JavaScript solution finds the kth smallest number in a multiplication table using binary search. The helper function `countLessOrEqual` calculates how many values are at most equal to the current midpoint, refining the search bounds based on these counts.
This approach uses a min-heap (priority queue) to keep track of the smallest unseen elements in the multiplication table. By continuously adding the next minimum elements from the rows, we can extract them in order until we reach the kth smallest element.
Time Complexity: O(k log m)
Space Complexity: O(m)
1import heapq
2
3def find_kth_number(m,
This Python solution utilizes a min-heap to access elements of the multiplication table in increasing order. We initially fill the heap with the first multiple of each row index and continually add the next multiple for extraction.