PPractick

DSA interview question

Find a Peak Element

Medium · Algorithms · Topics: binary search, array

The problem

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).

Function signature

int findPeakElement(const vector<int>& nums);  // index of any peak; adjacent values are distinct

Test cases

Input numsOutputExplanation
[1, 2, 3, 1]23 is higher than 2 and 1
[1, 2, 1, 3, 5, 6, 4]56 is a peak (index 1 would also be accepted)
[1]0A single element is a peak
[2, 1]0The 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.)

How interviewers phrase it

Clarifying questions to ask

  1. Is any peak acceptable, or a specific one?
  2. Are adjacent elements guaranteed to be different?
  3. How are the ends treated? (As bordered by minus infinity.)

Follow-ups to expect

  1. "How can binary search work on unsorted data?"
  2. "Why does the guarantee about adjacent values matter?"
  3. "Why hi = mid in the falling case?"
  4. "Complexity?"

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