Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding peak of a centrally peaked array in JavaScript
A centrally peaked array is an array that increases to a peak element and then decreases. It has the following properties:
Array length must be at least 3
-
There exists an index i where 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i-1] < arr[i] (strictly increasing)
arr[i] > arr[i+1] > ... > arr[arr.length - 1] (strictly decreasing)
Problem Statement
Given a centrally peaked array, find the index of the peak element. The peak element is the maximum element in the array where all elements to its left are smaller and all elements to its right are smaller.
Example Input and Output
Input:
const arr = [4, 6, 8, 12, 15, 11, 7, 4, 1];
Output:
4
Explanation: The element at index 4 is 15, which is the peak element of this array.
Solution Using Binary Search
Since the array has a single peak, we can use binary search to find it efficiently in O(log n) time complexity.
const arr = [4, 6, 8, 12, 15, 11, 7, 4, 1];
const findPeak = (arr = []) => {
if (arr.length {
if (low > high) {
return -1;
}
const middle = Math.floor((low + high) / 2);
// If middle element is smaller than next element, peak is on right side
if (arr[middle]
Peak index: 4
Peak value: 15
How It Works
The algorithm uses binary search with the following logic:
- Calculate the middle index of the current search range
- Compare the middle element with its neighbors:
- If middle ? next element: peak is on the right side
- If middle ? previous element: peak is on the left side
- If middle > both neighbors: middle is the peak
- Recursively search the appropriate half until the peak is found
Alternative Linear Search Approach
const findPeakLinear = (arr = []) => {
if (arr.length arr[i - 1] && arr[i] > arr[i + 1]) {
return i;
}
}
return -1;
};
const testArr = [3, 5, 8, 12, 9, 6, 2];
console.log("Linear search result:", findPeakLinear(testArr));
Linear search result: 3
Time Complexity Comparison
| Approach | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Binary Search | O(log n) | O(log n) | Large arrays |
| Linear Search | O(n) | O(1) | Small arrays |
Conclusion
Finding the peak of a centrally peaked array can be solved efficiently using binary search in O(log n) time. The key insight is that we can eliminate half of the search space by comparing the middle element with its neighbors.
