Given an array of integers, find all the peak elements. A peak element is an element that is greater than its neighbors. For corner elements, we need to consider only one neighbor. The goal is to return the indices of all the peak elements.
from typing import List
def find_peaks(nums: List[int]) -> List[int]:
if not nums:
return []
n = len(nums)
peaks = []
for i in range(n):
if i == 0:
# First element, compare to the next element
if n == 1 or nums[i] > nums[i + 1]:
peaks.append(i)
elif i == n - 1:
# Last element, compare to the previous element
if nums[i] > nums[i - 1]:
peaks.append(i)
else:
# Middle elements, compare to both neighbors
if nums[i] > nums[i - 1] and nums[i] > nums[i + 1]:
peaks.append(i)
return peaks
The time complexity of this solution is O(n), where n is the number of elements in the input array. This is because we are iterating through the array once to check for peak elements.
The space complexity is O(1) auxiliary space, given that we only use a few additional variables besides the input and output storage.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?