
Problem
Solution
Submissions
Peak Element in an Array
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C# program to find a peak element in an array. A peak element is an element that is strictly greater than its neighbors. If the array contains multiple peaks, return the index of any peak element.
For boundary elements (first and last), we only compare with the one neighbor they have.
Example 1
- Input: nums = [1,2,3,1]
- Output: 2
- Explanation:
- Index 2 is a peak because nums[2] = 3 is greater than its neighbors nums[1] = 2 and nums[3] = 1.
Example 2
- Input: nums = [1,2,1,3,5,6,4]
- Output: 5
- Explanation:
- Index 5 is a peak because nums[5] = 6 is greater than its neighbors nums[4] = 5 and nums[6] = 4.
- Index 2 is also a peak (nums[2] = 1), but we only need to return one peak index.
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
- A naive approach would be to scan the entire array linearly and check each element
- Can we use binary search to improve the time complexity?
- During binary search, we can determine which half of the array must contain a peak
- Check the middle element and its neighbors to determine search direction
- Remember to handle edge cases for boundary elements