Find a Peak Element II — LeetCode 1901 Python Solution
- Problem
- #1901
- Pattern
- Matrix and Grid
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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].
Example
- 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.
Python solution
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]))]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log m), where m and n are the number of rows and columns of the matrix, respectively |
| Space | O(1) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1901. Find a Peak Element II is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1901. Find a Peak Element II?
- LeetCode 1901. Find a Peak Element II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1901. Find a Peak Element II?
- The Python solution on this page runs in O(n \times \log m), where m and n are the number of rows and columns of the matrix, respectively.
- What is the space complexity of LeetCode 1901. Find a Peak Element II?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1901. Find a Peak Element II cover?
- LeetCode 1901. Find a Peak Element II is tagged Array, Binary Search and Matrix on LeetCode.