DSA interview question
A hiking app has elevation readings along a trail and wants to mark a summit: any point higher than both its neighbours (the trail's two ends count as having a "neighbour" at minus infinity). There may be many peaks, and any one will do. Scanning the trail is O(n), but binary search works even though the data isn't sorted. If the path is rising at mid (the next reading is higher), there must be a peak somewhere ahead; if it's falling, there must be a peak at mid or behind it.
Example: [1, 2, 3, 1] → 2 (the value 3).
int findPeakElement(const vector<int>& nums); // index of any peak; adjacent values are distinct
Input nums | Output | Explanation |
|---|---|---|
[1, 2, 3, 1] | 2 | 3 is higher than 2 and 1 |
[1, 2, 1, 3, 5, 6, 4] | 5 | 6 is a peak (index 1 would also be accepted) |
[1] | 0 | A single element is a peak |
[2, 1] | 0 | The left end counts, since nums[-1] is minus infinity |
[1, 2] | 1 | |
[5, 4, 3, 2, 1] | 0 |
(Confirm: nums[i] ≠ nums[i + 1] for all i; positions outside the array count as minus infinity; any peak index is accepted.)
hi = mid in the falling case?"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