Algorithm-Day21-Search-a-2D-Matrix-II-lc-240
π§© Problem Description
Write an efficient algorithm that searches for a value in an m x n
matrix.
This matrix has the following properties:
- Integers in each row are sorted in ascending order.
- Integers in each column are sorted in ascending order.
Example:
1 | Input: matrix = [ |
π‘ Naive Approach (Not Ideal)
- Scan the whole matrix: O(m Γ n) time.
- β Not efficient considering the sorted properties.
π‘ Optimal Approach: Search from Top-Right Corner
β¨ Key Idea
- Start from the top-right cell.
- At each step:
- If the value is equal to
target
, return true. - If the value is greater than
target
, move left. - If the value is less than
target
, move down.
- If the value is equal to
- Why it works:
- Rows increase left β right.
- Columns increase top β bottom.
π’ Java Code
1 | class Solution { |
β± Time and Space Complexity
- Time Complexity: O(m + n)
Worst case: we move from top-right to bottom-left. - Space Complexity: O(1)
No extra space used.
βοΈ Summary
- The staircase search pattern is a must-know technique for sorted 2D matrices.
- Itβs more efficient than binary search on each row or column separately.
- Similar sorted matrix problems:
lc-74 (Search a 2D Matrix)
lc-378 (Kth Smallest Element in a Sorted Matrix)
When rows and columns are sorted, think about combining row and column movement strategies instead of brute force search.