LeetCode 852: Peak Index in a Mountain Array Solution
Master LeetCode problem 852 (Peak Index in a Mountain Array), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
852. Peak Index in a Mountain Array
Problem Explanation
Explanation
To find the peak index in a mountain array in O(log(n)) time complexity, we can use a binary search approach.
- Initialize left and right pointers to the start and end indices of the array.
- While left < right: a. Calculate the mid index. b. If arr[mid] < arr[mid+1], peak must be on the right side of mid. Set left = mid + 1. c. Else, peak must be on the left side of mid. Set right = mid.
- Return left as the peak index.
Time complexity: O(log(n)) Space complexity: O(1)
Solution Code
class Solution {
public int peakIndexInMountainArray(int[] arr) {
int left = 0, right = arr.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (arr[mid] < arr[mid + 1]) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 852 (Peak Index in a Mountain Array)?
This page provides optimized solutions for LeetCode problem 852 (Peak Index in a Mountain Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 852 (Peak Index in a Mountain Array)?
The time complexity for LeetCode 852 (Peak Index in a Mountain Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 852 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 852 in Java, C++, or Python.