A peak element in an array is an element that is greater than or equal to its neighbors. Given an input array nums where nums[i] != nums[i+1], find a peak element and return its index.

The array may contain multiple peaks; it is sufficient to return any peak element’s index.

You may imagine that nums[-1] = nums[n] = -∞ where n is the length of the array.

Function Signature:

from typing import List

def find_peak_element(nums: List[int]) -> int:
    """
    Find a peak element in the input array.

    Parameters:
    - nums: A list of integers.

    Returns:
    - int: The index of the peak element.
    """
    # Your code here

Example:

result1 = find_peak_element([1, 2, 3, 1])
print(result1)
assert result1 == 2
# Explanation: The peak element is 3, and its index is 2.

result2 = find_peak_element([1, 2, 1, 3, 5, 6, 4])
print(result2)
assert result2 in [1, 5]
# Explanation: The peak elements are 2 and 6, and their indices are 1 and 5, respectively.

Note:

  • There may be multiple peak elements in the array. It is sufficient to return the index of any peak element.
  • The array nums is guaranteed to contain distinct integers.
  • The input array has at least one peak element.

Instructions:

  • Write the find_peak_element function to solve the problem.
  • Implement your solution in Python.
  • Provide clear comments in your code.
  • Discuss the time and space complexity of your solution.

As always, we’ll share our solution to this problem tomorrow. Stay tuned 😊