Find a Peak Element II Problem
Description
LeetCode Problem 1901.
A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom.
Given a 0-indexed m x n matrix mat where no two adjacent cells are equal, find any peak element mat[i][j] and return the length 2 array [i,j].
You may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell.
You must write an algorithm that runs in O(m log(n)) or O(n log(m)) time.
Example 1:

Input: mat = [[1,4],[3,2]]
Output: [0,1]
Explanation: Both 3 and 4 are peak elements so [1,0] and [0,1] are both acceptable answers.
Example 2:

Input: mat = [[10,20,15],[21,30,14],[7,16,32]]
Output: [1,1]
Explanation: Both 30 and 32 are peak elements so [1,1] and [2,2] are both acceptable answers.
Constraints:
m == mat.lengthn == mat[i].length1 <= m, n <= 5001 <= mat[i][j] <= 10^5- No two adjacent cells are equal.
Solution
Approach: Binary Search on Rows
Binary search over the rows. For the middle row mid, find the column j of its maximum. Compare mat[mid][j] with the cell below it:
- if
mat[mid][j] > mat[mid + 1][j], a peak exists in rows0..mid, so setr = mid; - otherwise a peak exists in rows
mid + 1..m - 1, so setl = mid + 1.
Why it is safe: suppose mat[mid][j] is larger than the cell below but no peak existed in the rows above. Then the row maximum would have to be beaten by the row above it, and again, and so on, each row's maximum being larger than the previous; this cannot go on forever, because the top boundary is surrounded by -1, so a peak must be found. The other case is symmetric.
When l == r, the maximum of that row is a peak.
Complexity: O(n log m) time and O(1) space for an m x n matrix.
class Solution:
def findPeakGrid(self, mat: List[List[int]]) -> List[int]:
l, r = 0, len(mat) - 1
while l < r:
mid = (l + r) >> 1
j = mat[mid].index(max(mat[mid]))
if mat[mid][j] > mat[mid + 1][j]:
r = mid
else:
l = mid + 1
return [l, mat[l].index(max(mat[l]))]