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,1]
💡 Note: Element 7 at [1,1] is greater than all neighbors: 7 > 4 (top), 7 > 2 (left), 7 > 6 (right), 7 > 0 (bottom).
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 II INPUT 2D Matrix (3x5) 1 4 3 2 0 2 7 6 1 3 5 0 1 4 8 Global Max (7) Peak [1,2] = 6 Another Peak (8) Input Values mat = [ [1,4,3,2,0], [2,7,6,1,3], [5,0,1,4,8] ] m=3 rows, n=5 cols ALGORITHM STEPS 1 Binary Search on Cols Start with mid column mid = (0+4)/2 = 2 2 Find Max in Column Col 2: [3,6,1] Max = 6 at row 1 3 Check Neighbors Left: 7, Right: 1 7 > 6? Move left 4 Repeat Until Peak Col 1: max=7 at row 1 Left:2, Right:6 both < 7 Peak found! Binary Search Flow 0 1 2 3 4 mid=2 PEAK! FINAL RESULT Peak Element Found 4 ... 3 2 7 6 5 0 1 Peak Verification mat[1][1] = 7 Top: 4 < 7 OK Bottom: 0 < 7 OK Left: 2 < 7 OK Right: 6 < 7 OK OUTPUT [1, 1] [1,2] or [2,4] also valid Key Insight: Binary search on columns: find max element in mid column, then compare with left/right neighbors. If neighbor is larger, peak must exist in that direction (guaranteed by -1 boundary). Time Complexity: O(m log n) - log n binary search iterations, O(m) to find column max each time. TutorialsPoint - Find a Peak Element II | Optimal Binary Search Solution
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