Skip to main content
Back to problems
#1901
Medium Algorithms

Find a peak element ii

Array Binary Search Matrix
54.4% acceptance
Feb 25, 2026
2673
162
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.

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn find_peak_grid(mat: Vec<Vec<i32>>) -> Vec<i32> {
    let m = mat.len();
    let mut lo = 0usize;
    let mut hi = m - 1;
    while lo <= hi {
      let mid = lo + (hi - lo) / 2;
      let max_col = mat[mid].iter().enumerate().max_by_key(|&(_, v)| v).unwrap().0;
      let up = if mid > 0 { mat[mid - 1][max_col] } else { -1 };
      let down = if mid < m - 1 { mat[mid + 1][max_col] } else { -1 };
      if mat[mid][max_col] > up && mat[mid][max_col] > down {
        return vec![mid as i32, max_col as i32];
      } else if up > mat[mid][max_col] {
        hi = mid - 1;
      } else {
        lo = mid + 1;
      }
    }
    vec![]
  }
}