![]() |
VOOZH | about |
Find the middle element when the numbers in an n × n multiplication table are sorted in increasing order. It is assumed that n is odd.
For example, the 3 × 3 multiplication table is as follows:
1 2 3
2 4 6
3 6 9
The numbers in increasing order are [1,2,2,3,3,4,6,6,9], so the answer is 3
Input:
n = 3
Output:3
Explanation: The3x3multiplication table is as follows:1 2 3
2 4 6
3 6 9The sorted elements are:
[1, 2, 2, 3, 3, 4, 6, 6, 9]. The middle element is3.Input:
n = 5
Output:8
Explanation: The5x5multiplication table is as follows:1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25The sorted elements are:
[1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 6, 8, 8, 9, 10, 10, 12, 12, 15, 15, 16, 20, 20, 25]. The middle element is8.
The main observation here is to realize that we can use binary search to efficiently determine the middle element in the
n x nmultiplication table. We don't need to explicitly construct and sort the table, but rather use the properties of the multiplication table to count elements up to a certain value.
- Binary Search Range: The minimum value in the multiplication table is
1and the maximum value isn * n.- Counting Elements: For a given middle value
mid, count how many numbers in the multiplication table are less than or equal tomid. This can be done row by row. For rowi, the elements arei, 2*i, 3*i, ..., n*i. The number of elements in this row that are ≤midismin(n, ⌊mid / i⌋).- Adjusting Search Range: Use binary search to find the smallest value
midfor which the count of elements ≤midis at least(n^2 + 1) / 2(the middle position in the sorted list).
Step-by-step approach:
low = 1 and high = n * n.low < high:mid = (low + high) / 2.mid.(n^2 + 1) / 2, set high = mid.low = mid + 1.high as the middle element.Below is the implementation of the above algorithm:
3 8
Time Complexity: O(n*log(n*n))
Auxiliary Space: O(1)