Find a Peak Element II - 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].

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.

Input & Output

Example 1 — Basic 3x3 Matrix
$ Input: mat = [[1,4,3,2,0],[2,7,6,1,3],[5,0,1,4,8]]
Output: [1,2]
💡 Note: Element at [1,2] is 6. It's greater than neighbors: 6 > 4 (top), 6 > 7 is false... Actually, 7 at [1,1] is greater than all neighbors: 7 > 4, 7 > 2, 7 > 6, 7 > 0. So return [1,1].
Example 2 — Single Peak
$ Input: mat = [[10,20,15],[21,30,14],[7,16,32]]
Output: [1,1]
💡 Note: Element 30 at [1,1] is greater than all neighbors: 30 > 20, 30 > 21, 30 > 14, 30 > 16
Example 3 — Corner Peak
$ Input: mat = [[1,2],[3,4]]
Output: [1,1]
💡 Note: Element 4 at [1,1] is greater than all neighbors: 4 > 3, 4 > 2. Boundary cells have value -1.

Constraints

  • m == mat.length
  • n == mat[i].length
  • 1 ≤ m, n ≤ 500
  • -105 ≤ mat[i][j] ≤ 105
  • No two adjacent cells are equal

Visualization

Tap to expand
Find a Peak Element IIInput Matrix:143276501Peak Definition:• Element > top neighbor• Element > left neighbor• Element > right neighbor• Element > bottom neighbor7 > 4, 7 > 2, 7 > 6, 7 > 0 ✓Output: [1, 1]Any valid peak coordinates
Understanding the Visualization
1
Input Matrix
2D grid where we need to find any peak element
2
Peak Definition
Element greater than all 4 neighbors (left, right, top, bottom)
3
Output
Return coordinates [row, col] of any peak element
Key Takeaway
🎯 Key Insight: Use binary search to eliminate half the search space by comparing column maximums with their neighbors
Asked in
Google 25 Facebook 18 Amazon 15 Microsoft 12
28.5K Views
Medium-High Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen