#240
Search a 2D Matrix II
MediumArrayBinary SearchDivide and ConquerMatrixTwo PointersBinary SearchMatrix Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + m) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n + m)Space O(1)
We can leverage the sorted properties of the matrix. Start from the top-right corner and move left if the current number is greater than the target or down if it’s less than the target. This way, we can eliminate entire rows or columns in each step.
⚙️
Algorithm
6 steps- 1Step 1: Start at the top-right corner of the matrix.
- 2Step 2: Compare the current element with the target.
- 3Step 3: If the current element equals the target, return true.
- 4Step 4: If the current element is greater than the target, move left (decrease column index).
- 5Step 5: If the current element is less than the target, move down (increase row index).
- 6Step 6: Repeat until you go out of bounds or find the target.
solution.py10 lines
1# Full working Python code
2row, col = 0, len(matrix[0]) - 1
3while row < len(matrix) and col >= 0:
4 if matrix[row][col] == target:
5 return True
6 elif matrix[row][col] > target:
7 col -= 1
8 else:
9 row += 1
10return Falseℹ
Complexity note: This complexity is efficient because we only traverse the matrix in a linear fashion, either moving left or down, which results in at most m + n steps.
- 1Utilizing the sorted properties of the matrix allows for more efficient searching.
- 2Moving strategically through the matrix can reduce the number of comparisons needed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.