
Problem
Solution
Submissions
Find Peak Element
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript program to find a peak element in an array. A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums, find a peak element and return its index. If the array contains multiple peaks, return the index to any one of the peaks. You may imagine that nums[-1] = nums[n] = -∞. The algorithm should run in O(log n) time complexity.
Example 1
- Input: nums = [1,2,3,1]
- Output: 2
- Explanation:
- Check element at index 2, which has value 3.
- Compare with left neighbor: 3 > 2 (at index 1).
- Compare with right neighbor: 3 > 1 (at index 3).
- Since 3 is greater than both neighbors, index 2 is a peak.
- Check element at index 2, which has value 3.
Example 2
- Input: nums = [1,2,1,3,5,6,4]
- Output: 5
- Explanation:
- The array has multiple peaks at indices 1 and 5.
- Element at index 1 has value 2: 2 > 1 (left) and 2 > 1 (right).
- Element at index 5 has value 6: 6 > 5 (left) and 6 > 4 (right).
- Either index 1 or 5 can be returned as both are valid peaks.
- The array has multiple peaks at indices 1 and 5.
Constraints
- 1 ≤ nums.length ≤ 1000
- -2^31 ≤ nums[i] ≤ 2^31 - 1
- nums[i] != nums[i + 1] for all valid i
- Time Complexity: O(log n)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use binary search to achieve O(log n) time complexity
- Compare the middle element with its right neighbor to determine search direction
- If nums[mid] < nums[mid + 1], the peak must be on the right side
- If nums[mid] > nums[mid + 1], the peak could be at mid or on the left side
- Continue binary search until you find a peak element
- Handle edge cases for single element array and boundary elements