![]() |
VOOZH | about |
Given three integers n, m, and k. Consider a multiplication table of size n × m (with 1-based indexing), where the value at each cell (i, j) is defined as: mat[i][j] = i × j. That is, the cell at row i and column j contains the product of i and j.
Find the k-th smallest element in this multiplication table.
Examples:
Input: n = 2, m = 3, k = 5
Output: 4
Explanation:
Multiplication Table: [[1, 2, 3],
[2, 4, 6]]
Sorted Elements are [1, 2, 2, 3, 4, 6], then 5th smallest element is 4.Input: n = 3, m = 2, k = 4
Output: 3
Explanation:
Multiplication Table: [[1, 2],
[2, 4],
[3, 6]]
Sorted Elements are [1, 2, 2, 3, 4, 6], then 4th smallest element is 3.
Table of Content
The approach generates all values in the n × m multiplication table by computing i × j for every cell, stores them in a list, and sorts the list. After sorting, the k-th smallest element is simply the element at index k - 1. This is a brute-force method and works well for small sizes.
4
The idea is similar to kth Smallest Element using Max Heap. We generate all values of the form (i × j) and maintain a max heap of size k. If the current element is smaller than the largest element in our heap, we replace the largest element with the current one. At the end, the Max Heap root contains kth smallest values.
Step by step implementation:
4
Instead of generating all n × m elements, we define the search range from 1 to n × m and use binary search to find the value where exactly k elements in the table are smaller than or equal to it. We count smaller values than the current mid value. If the count is more than k, we go the right half, else we go the left half.
How can we count values less than equal to x?
To count values less than or equal to a given number x in the multiplication table, we iterate through each row i from 1 to n and count how many elements in that row are less than or equal to x. For each row i, the elements are i, 2×i, 3×i, ..., m×i, so there are min(x/i, m) such elements in row i.
4