Algorithm Day65 - Search a 2D Matrix
🧩 Problem Description
You are given an m x n integer matrix matrix with the following properties:
- Each row is sorted in ascending order.
- The first integer of each row is greater than the last integer of the previous row.
Given an integer target, return true if target is in the matrix or false otherwise.
💬 Examples
Example 1
1 | Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 |
Example 2
1 | Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 |
💡 Intuition
The matrix has a special structure:
- If we flatten it into a single array, it is fully sorted.
- Thus, we can apply binary search over the virtual array.
Mapping from index in flattened array:
row = mid / ncol = mid % n
🔢 Java Code (Binary Search)
1 | class Solution { |
⏱ Complexity Analysis
- Time: O(log(m × n)) — binary search on
m*nelements. - Space: O(1) — only pointers are used.
✍️ Summary
- Flatten the 2D matrix into a sorted 1D array conceptually.
- Apply binary search on indices.
Related problems
lc-240— Search a 2D Matrix IIlc-33— Search in Rotated Sorted Array