Problem Description
Given an m x n integer matrix where each row is sorted in ascending order from left to right and each column is sorted in ascending order from top to bottom, determine if the target integer exists in the matrix.
Key Insights
- Each row and column is sorted, which allows us to eliminate multiple rows or columns with one comparison.
- Starting from the top-right corner (or bottom-left) is beneficial because at this position, one can decide to move left or down based on how the current value compares with the target.
- This "staircase" search leads to a linear time algorithm relative to the sum of dimensions of the matrix.
Space and Time Complexity
Time Complexity: O(m + n) where m is the number of rows and n is the number of columns. Space Complexity: O(1)
Solution
The algorithm starts from the top-right corner of the matrix. At each step, compare the current element with the target:
- If the current element equals the target, return true.
- If the current element is greater than the target, move left because all elements below are larger.
- If the current element is smaller than the target, move down because all elements to the left are smaller. This method ensures that in each step one row or one column is eliminated from consideration, leading to an efficient search.