Find Peak Element
Updated
Problem statement
A peak is an element that is strictly greater than its neighbours. Treat the positions just outside the array as -∞, so the first or last element can be a peak.
You are given an integer array nums that has exactly one peak. Return the index of the peak.
Aim for O(log n) time.
Function
findPeakElement(nums: int[]) → intExamples
Example 1
nums = [1,3,5,4,2]return = 2The values rise to 5 and then fall. nums[2] = 5 is greater than both neighbours, 3 and 4, so the answer is 2.
Example 2
nums = [2,4,6,8]return = 3The values only rise. The last element, 8, is greater than its left neighbour, and there is no right neighbour, so it counts as a peak. The answer is 3.
Example 3
nums = [9]return = 0A single element has no neighbours, so it is the peak. The answer is 0.
Constraints
1 <= nums.length <= 10^4-10^9 <= nums[i] <= 10^9nums[i] != nums[i + 1]for every validi.numshas exactly one peak: it strictly rises and then strictly falls, and either part may be empty.
More Microsoft Onsite Interview questions
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Valid ParenthesesONSITE INTERVIEW · Seen Nov 2026
- Count a User's Actions in an Event LogONSITE INTERVIEW · Seen Nov 2026
- Smallest Batch Size Within a Step LimitONSITE INTERVIEW · Seen Nov 2026
- Count Subarrays with Equal Even and Odd CountsONSITE INTERVIEW · Seen Nov 2026
- Minimum Time to Rot All OrangesONSITE INTERVIEW · Seen Nov 2026
- Coin ChangeONSITE INTERVIEW · Seen Oct 2026
- Daily USD Totals with Effective-Dated Exchange RatesONSITE INTERVIEW · Seen Oct 2026
- Number Words to Digits in Any LanguageONSITE INTERVIEW · Seen Oct 2026
- Totals from a Tiered Rate TableONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Search a Row- and Column-Sorted MatrixByteDance · ONSITE INTERVIEWByteDance interview questions
- First and Last Target Position in a Mountain ArrayGoogle · ONSITE INTERVIEWGoogle interview questions
- 3Sum SmallerSalesforce · ONSITE INTERVIEWSalesforce interview questions
- Peak of an Increasing-Then-Decreasing ArraySnap Inc. · ONSITE INTERVIEWSnap Inc. interview questions
- Online Meeting Scheduler with Fixed RoomsUber · ONSITE INTERVIEWUber interview questions
- Search in a Rotated Sorted ArrayAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Search in Rotated Sorted ArrayKotak Mahindra Bank · ONSITE INTERVIEWKotak Mahindra Bank interview questions
- Find First and Last Position in Sorted ArrayPaytm · ONSITE INTERVIEWPaytm interview questions
- Detect a Silent SensorConfluent · ONSITE INTERVIEWConfluent interview questions
- Search in Rotated Sorted ArrayCapgemini · ONSITE INTERVIEWCapgemini interview questions