mediumArraysPattern: Modified Binary Search

Peak Index Locator Solution

Problem Statement

Given a non-empty array of integers `mountainSequence`, find the index of the peak element, where the sequence initially increases and then strictly decreases.

Examples

Example 1:
Input:[1,2,3,4,5,4,3,2,1]
Output:4
Explanation: The peak element in the given mountain sequence is 5, which is at index 4
Example 2:
Input:[0,1,2,3,2,1,0]
Output:3
Explanation: The peak element in the given mountain sequence is 3, which is at index 3

Constraints

  • 1 <= array length <= 10^5
  • Array represents a mountain sequence
  • All elements are distinct integers
  • Array is not empty
  • Only one peak element exists
Time: O(log n) Space: O(1)
The optimal approach is to use a modified binary search algorithm, which takes advantage of the mountain sequence structure to find the peak element in O(log n) time complexity. This approach divides the search space in half at each step.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.