DSA interview question
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).
vector<int> findPeakGrid(const vector<vector<int>>& mat); // {row, col} of any peak
Input mat | Output | Explanation |
|---|---|---|
[[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.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in