algoadvance

Leetcode 852. Peak Index in a Mountain Array

Problem Statement

Given a mountain array arr, return the index i such that the following conditions hold:

You must solve it in O(log(arr.length)) time complexity.

Example:

Input: arr = [0,2,1,0]
Output: 1

Constraints:

Clarifying Questions

  1. Is the array guaranteed to be a valid mountain array?
    • Yes, it is explicitly mentioned in the problem statement.
  2. Can there be duplicate values in the array?
    • No, given the description, the array values are strictly increasing and then strictly decreasing.

Strategy

Given the constraints and the requirement for O(log n) time complexity, a binary search approach is ideal.

Code

#include <vector>

class Solution {
public:
    int peakIndexInMountainArray(std::vector<int>& arr) {
        int left = 0, right = arr.size() - 1;
        
        while (left < right) {
            int mid = left + (right - left) / 2;
            
            if (arr[mid] < arr[mid + 1]) {
                // We are in the ascending part of the mountain
                left = mid + 1;
            } else {
                // We are in the descending part of the mountain, or at the peak
                right = mid;
            }
        }
        
        // left and right converge to the peak index
        return left;
    }
};

Time Complexity

This solution ensures that we efficiently find the peak index in the mountain array using the constraints provided.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI