
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)
1def count_less_equal(m, n, x):
2 count = 0
3 for i in range(1, m + 1):
4 count += min(x // i, n)
5 return count
6
7def find_kth_number(m, n, k):
8 low, high = 1, m * n
9 while low < high:
10 mid = (low + high) // 2
11 if count_less_equal(m, n, mid) < k:
12 low = mid + 1
13 else:
14 high = mid
15 return low
16
17print(find_kth_number(3, 3, 5)) # Output: 3In this Python solution, we use binary search to find the kth smallest number in the multiplication table. A helper function `count_less_equal` checks the number of multiples less than or equal to a given number, which helps guide the search.
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.