Magicsheet logo

Find a Peak Element II

Medium
60.8%
Updated 6/1/2025

Find a Peak Element II

What is this problem about?

The Find a Peak Element II coding problem is a multidimensional extension of the classic peak finding challenge. Given a 2D matrix where no two adjacent cells are equal, a "peak" is an element that is strictly greater than all its immediate neighbors (up, down, left, and right). Your task is to find the coordinates of any one such peak element in O(NlogM)O(N \log M) or O(MlogN)O(M \log N) time.

Why is this asked in interviews?

This problem is a favorite at Microsoft and Google because it tests your ability to optimize a search in a 2D space. A brute-force scan would take O(NimesM)O(N imes M), but the logarithmic requirement forces you to apply the Binary Search interview pattern in a clever way. It evaluations whether you can reduce a complex 2D search into a 1D decision process by identifying properties that guarantee the existence of a solution in a specific sub-region.

Algorithmic pattern used

This problem uses a combination of Binary Search and Global Maximum finding.

  1. Pick a middle column.
  2. Find the maximum element in that specific column (which takes O(N)O(N) time).
  3. Compare this global column maximum with its neighbors in the adjacent columns (left and right).
  4. If it's greater than both, it's a peak.
  5. If the neighbor to the left is larger, a peak must exist in the left half of the matrix.
  6. If the neighbor to the right is larger, a peak must exist in the right half.
  7. Repeat the process on the chosen half.

Example explanation

Imagine a 3imes33 imes 3 matrix:

[ 1, 4, 3 ]
[ 2, 5, 2 ]
[ 3, 6, 4 ]
  1. Choose middle column (Index 1): [4, 5, 6].
  2. Max in this column is 6 (at row 2, col 1).
  3. Compare 6 with neighbors: 3 (left) and 4 (right).
  4. Since 6 > 3 and 6 > 4, 6 is a peak element.
  5. Return [2, 1].

Common mistakes candidates make

  • Applying 1D binary search incorrectly: Trying to binary search every row independently, which doesn't guarantee a peak relative to vertical neighbors.
  • Complexity errors: Implementing an O(NimesM)O(N imes M) solution when O(NlogM)O(N \log M) is required.
  • Boundary conditions: Not correctly handling cases where the "middle" column is at the very edge of the matrix.

Interview preparation tip

Whenever you need to solve a 2D problem in better than linear time, think about "Dimensional Reduction." Can you solve a 1D version of the problem at a specific index and use that result to eliminate half of the remaining 2D space? This is a core Matrix interview pattern.

Similar Questions