Solving Leetcode Interviews in Seconds with AI: Peak Index in a Mountain Array
Introduction
In this blog post, we will explore how to solve the LeetCode problem "852" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
You are given an integer mountain array arr of length n where the values increase to a peak element and then decrease. Return the index of the peak element. Your task is to solve it in O(log(n)) time complexity. Example 1: Input: arr = [0,1,0] Output: 1 Example 2: Input: arr = [0,2,1,0] Output: 1 Example 3: Input: arr = [0,10,5,2] Output: 1 Constraints: 3 <= arr.length <= 105 0 <= arr[i] <= 106 arr is guaranteed to be a mountain array.
Explanation
Here's the approach to find the peak element in a mountain array efficiently:
- Binary Search: Utilize binary search to narrow down the search space by repeatedly dividing the array into halves.
- Peak Identification: In each iteration, compare the middle element with its neighbors to determine if it's the peak or if the peak lies in the left or right half.
Termination: Continue the binary search until the peak element is found.
Runtime Complexity: O(log n), Storage Complexity: O(1)
Code
def peakIndexInMountainArray(arr):
"""
Finds the index of the peak element in a mountain array.
Args:
arr: A list of integers representing the mountain array.
Returns:
The index of the peak element.
"""
left, right = 0, len(arr) - 1
while left < right:
mid = (left + right) // 2
if arr[mid] < arr[mid + 1]:
left = mid + 1 # Peak is to the right
else:
right = mid # Peak is mid or to the left
return left