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 kth smallest element in the m x n multiplication table.
Example 1:
Input: m = 3, n = 3, k = 5 Output: 3 Explanation: The 5th smallest number is 3.
Example 2:
Input: m = 2, n = 3, k = 6 Output: 6 Explanation: The 6th smallest number is 6.
Constraints:
1 <= m, n <= 3 * 1041 <= k <= m * nThe 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.
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.
C++
Java
Python
C#
JavaScript
Time Complexity: O(m * log(m * n))
Space Complexity: O(1)
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.
This C++ code uses a min-heap to track the smallest values efficiently. We insert initial multiples from each row into the heap and extract the smallest at each step, pushing the next element from the same row.
Python
Time Complexity: O(k log m)
Space Complexity: O(m)
| Approach | Complexity |
|---|---|
| Binary Search Method | Time Complexity: O(m * log(m * n)) |
| Priority Queue (Heap) Method | Time Complexity: O(k log m) |
Kth Smallest Element in a BST - Leetcode 230 - Python • NeetCode • 207,441 views views
Watch 9 more video solutions →Practice Kth Smallest Number in Multiplication Table with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor