PPractick

DSA interview question

Find a Peak Element II (2D Peak)

Medium · Algorithms · Topics: binary search, matrix, divide and conquer

The problem

A terrain-analysis tool has a grid of elevations where no two adjacent cells have the same height. It needs to report any peak: a cell strictly higher than its up, down, left and right neighbours (cells outside the grid count as −1). Scanning every cell is O(m·n). The 1D peak trick extends to 2D. Binary-search over columns; in the middle column, take the maximum cell, which is already higher than its vertical neighbours. Then compare it with its left and right neighbours and move towards the higher one, just like climbing a slope.

Example: [[10, 20, 15], [21, 30, 14], [7, 16, 32]] → [1, 1] (30 beats 20, 16, 21 and 14).

Function signature

vector<int> findPeakGrid(const vector<vector<int>>& mat);  // {row, col} of any peak

Test cases

Input matOutputExplanation
[[1, 4], [3, 2]][1, 0]3 beats 1 and 2 (4 at [0, 1] is also a valid peak)
[[10, 20, 15], [21, 30, 14], [7, 16, 32]][1, 1]30 (32 at [2, 2] is also valid)
[[1]][0, 0]
[[1, 2, 3, 4, 5]][0, 4]A single row: the slope rises to the end
[[5], [4], [3]][0, 0]A single column

(Confirm: adjacent cells differ; outside cells count as −1; any peak is accepted, and the code checks the peak property on random grids.)

How interviewers phrase it

Clarifying questions to ask

  1. Is any peak acceptable?
  2. Are adjacent values guaranteed to differ?
  3. How are border cells treated? (Outside counts as −1.)

Follow-ups to expect

  1. "Why take the column maximum?"
  2. "Why move towards the larger horizontal neighbour?"
  3. "What's the complexity?"
  4. "Could you binary-search rows instead?"
  5. "Why doesn't simple hill-climbing from a random cell work well?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in