
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)
1#include <stdio.h>
2
3int countLessOrEqual(int m, int n, int x) {
4 int count = 0;
5 for (int i = 1; i <= m; i++) {
6 count += (x / i < n) ? x / i : n;
7 }
8 return count;
9}
10
11int findKthNumber(int m, int n, int k) {
12 int low = 1, high = m * n;
13 while (low < high) {
14 int mid = low + (high - low) / 2;
15 if (countLessOrEqual(m, n, mid) < k)
16 low = mid + 1;
17 else
18 high = mid;
19 }
20 return low;
21}
22
23int main() {
24 int m = 3, n = 3, k = 5;
25 printf("%d\n", findKthNumber(m, n, k)); // Output: 3
26 return 0;
27}This C solution implements the binary search technique to find the kth smallest number in the multiplication table. The function `countLessOrEqual` computes how many numbers are less than or equal to the given value x. In the main logic, binary search narrows down the potential candidates for the kth smallest number.
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, n
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.