Leetcode 162: Find Peak Element

grid47
grid47
Exploring patterns and algorithms
Oct 21, 2024 6 min read

A smooth curve of numbers with the highest point glowing brightly, symbolizing the peak.
Solution to LeetCode 162: Find Peak Element Problem

You are given a list of integers, nums. A peak element is an element that is strictly greater than its neighbors. You need to find and return the index of any peak element in the list. The algorithm should run in O(log n) time.
Problem
Approach
Steps
Complexity
Input: The input consists of a list of integers, nums. The list has at least one element.
Example: [1, 3, 2, 1]
Constraints:
• 1 <= nums.length <= 1000
• -231 <= nums[i] <= 231 - 1
• nums[i] != nums[i + 1] for all valid i.
Output: The output should be the index of any peak element in the list.
Example: 1
Constraints:
• There will always be at least one peak element in the array.
Goal: The goal is to find the peak element index in O(log n) time.
Steps:
• Perform a binary search to find the peak element.
• Check if the middle element is greater than its neighbors.
• If the middle element is a peak, return its index.
• If the left neighbor is greater, search the left half of the array.
• If the right neighbor is greater, search the right half of the array.
Goal: The array length will always be at least 1, and there will always be at least one peak element.
Steps:
• The array will have at least one peak element.
• The algorithm must run in O(log n) time.
Assumptions:
• The array will always contain at least one peak element.
Input: [1, 3, 2, 1]
Explanation: In this example, the element 3 is the peak element as it is greater than its neighbors 1 and 2. Therefore, the function returns index 1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus