#1901
Find a Peak Element II
MediumArrayBinary SearchMatrixBinary SearchDivide and Conquer
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(m log(n)) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(m log(n))Space O(1)
The optimal solution uses a binary search approach to efficiently find a peak by reducing the search space in half at each step. This is akin to finding a needle in a haystack by eliminating half of the haystack with each guess.
⚙️
Algorithm
4 steps- 1Step 1: Start with the entire matrix and choose the middle column.
- 2Step 2: Find the maximum element in this column.
- 3Step 3: Check if this maximum element is a peak. If yes, return its coordinates.
- 4Step 4: If the maximum element has a neighbor that is greater, move to that neighbor's row and repeat the process.
solution.py20 lines
1# Full working Python code
2
3def findPeakGrid(mat):
4 m, n = len(mat), len(mat[0])
5 left, right = 0, n - 1
6 while left < right:
7 mid = (left + right) // 2
8 max_row = 0
9 for i in range(m):
10 if mat[i][mid] > mat[max_row][mid]:
11 max_row = i
12 if (mid == n - 1 or mat[max_row][mid] > mat[max_row][mid + 1]):
13 return [max_row, mid]
14 else:
15 left = mid + 1
16 max_row = 0
17 for i in range(m):
18 if mat[i][left] > mat[max_row][left]:
19 max_row = i
20 return [max_row, left]ℹ
Complexity note: The time complexity is O(m log(n)) because we perform a binary search on the columns, and for each column, we scan through all rows to find the maximum element. The space complexity is O(1) since we only use a constant amount of extra space.
- 1A peak can be found efficiently by reducing the search space using binary search.
- 2The problem can be approached from either row or column perspectives, depending on the dimensions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.