Skip to the solution
MediumDSA9 min read

How do you find a peak element in an array?

347 views

The problem

Question presented to candidate: "Given an integer array where no two neighbours are equal, return the index of any peak โ€” an element bigger than both its neighbours, with the outside of the array counting as minus infinity. Please write it in Python and aim for better than linear time."

What a strong answer should cover:

  • A peak always exists because out-of-range neighbours are minus infinity; any peak is accepted, not only the maximum.
  • The O(n) scan first, then binary search on the slope: compare nums[mid] with nums[mid + 1] and keep the half that must contain a peak.
  • The loop invariant that justifies it, and why the loop is while lo < hi with hi = mid.
  • O(log n) time and O(1) extra space; why the global maximum cannot be found this fast.
  • Python specifics: // for integer division (/ returns a float that cannot index a list), no integer overflow in (lo + hi) // 2, and an explicit check for an empty list.

Clarifying questions expected:

  • "Any peak or the highest one?"
  • "Can neighbours be equal?"
  • "What should an empty list return?"

Code / implementation expected: Yes โ€” a short iterative find_peak(nums) function in Python.

  • binary-search
  • arrays

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read ยท 13 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonFind a peak on six inputs, including edge cases
PythonTrace the search, brute-force check 1,456 arrays, and count the work

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 99 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you count subarrays that sum to k?

Continue