#74
Search a 2D Matrix
MediumArrayBinary SearchMatrixBinary SearchMatrix Search
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(m * n) | O(log(m * n)) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(log(m * n))Space O(1)
Since the matrix is sorted in a specific way, we can treat it as a single sorted array and use binary search to find the target efficiently.
⚙️
Algorithm
7 steps- 1Step 1: Initialize two pointers, left at 0 and right at m * n - 1 (total number of elements - 1).
- 2Step 2: While left <= right, calculate the mid index as (left + right) // 2.
- 3Step 3: Convert mid index to 2D coordinates: row = mid // n and col = mid % n.
- 4Step 4: If matrix[row][col] equals target, return true.
- 5Step 5: If matrix[row][col] is less than target, move left pointer to mid + 1.
- 6Step 6: If matrix[row][col] is greater than target, move right pointer to mid - 1.
- 7Step 7: If the loop ends, return false.
solution.py15 lines
1def searchMatrix(matrix, target):
2 if not matrix:
3 return False
4 m, n = len(matrix), len(matrix[0])
5 left, right = 0, m * n - 1
6 while left <= right:
7 mid = (left + right) // 2
8 mid_val = matrix[mid // n][mid % n]
9 if mid_val == target:
10 return True
11 elif mid_val < target:
12 left = mid + 1
13 else:
14 right = mid - 1
15 return Falseℹ
Complexity note: This complexity is achieved by treating the matrix as a flat array and applying binary search, which reduces the search space logarithmically.
- 1The matrix is sorted both row-wise and column-wise, allowing for efficient searching.
- 2Binary search can be applied in a 2D context by treating the matrix as a single sorted array.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.