Problem
Let A
be an N by M
matrix in which every row and every column is sorted.
Given i1
, j1
, i2
, and j2
, compute the number of elements of M smaller than M[i1, j1]
and larger than M[i2, j2]
.
Examples
Example 1
$$ \begin{array}{|c|c|c|c|c|c|} \hline 1 & 3 & 7 & 10 & 15 & 20 \\ \hline 2 & \colorbox{orange} 6 & 9 & 14 & 22 & 25 \\ \hline 3 & 8 & 10 & 15 & 25 & 30 \\ \hline 10 & 11 & 12 & \colorbox{green} {23} & 30 & 35 \\ \hline 20 & 25 & 30 & 35 & 40 & 45 \\ \hline \end{array} $$
|
|
Solution
Method 1 - Binary Search
The matrix is sorted in both rows and columns. Given this, we can leverage binary search to count the number of elements smaller than A[i1][j1]
and larger than A[i2][j2]
efficiently. Binary search allows us to quickly determine the number of elements satisfying the given conditions in each row.
Approach
- Count Elements Smaller than
A[i1][j1]
: For each row, use binary search to find the count of elements smaller thanA[i1][j1]
. - Count Elements Larger than
A[i2][j2]
: For each row, use binary search to find the count of elements larger thanA[i2][j2]
. - Sum the Results: Sum the counts from both steps to get the total number of elements that are either smaller than
A[i1][j1]
or larger thanA[i2][j2]
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(N * log M)
, whereN
is the number of rows andM
is the number of columns. This is because binary search is applied to each row. - 🧺 Space complexity:
O(1)
, as we only use a constant amount of extra space.