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 all peaks and their positions in an array in JavaScript
A peak (local maximum) in an array is an element that is greater than both its neighbors. Finding all peaks and their positions is useful for data analysis, signal processing, and identifying trends.
Problem Statement
Given an array of integers, we need to find all local maxima (peaks) and return an object containing two arrays: maximas (the peak values) and positions (their indices).
Consider this array:
const arr = [4, 3, 4, 7, 5, 2, 3, 4, 3, 2, 3, 4];
console.log("Array:", arr);
Array: [4, 3, 4, 7, 5, 2, 3, 4, 3, 2, 3, 4]
Visually, this array has peaks at index 3 (value 7) and index 7 (value 4), where each element is greater than both its left and right neighbors.
Algorithm
To find peaks, we iterate through the array (excluding first and last elements) and check if each element is greater than both neighbors. We also handle plateaus by checking consecutive equal values.
Implementation
const arr = [4, 3, 4, 7, 5, 2, 3, 4, 3, 2, 3, 4];
const findMaxima = (arr = []) => {
let positions = [];
let maximas = [];
for (let i = 1; i < arr.length - 1; i++) {
if (arr[i] > arr[i - 1]) {
if (arr[i] > arr[i + 1]) {
// Simple peak found
positions.push(i);
maximas.push(arr[i]);
} else if (arr[i] === arr[i + 1]) {
// Handle plateau
let temp = i;
while (i < arr.length - 1 && arr[i] === arr[temp]) {
i++;
}
if (i < arr.length && arr[temp] > arr[i]) {
positions.push(temp);
maximas.push(arr[temp]);
}
i--; // Adjust for loop increment
}
}
}
return { maximas, positions };
};
console.log(findMaxima(arr));
{ maximas: [ 7, 4 ], positions: [ 3, 7 ] }
How It Works
The algorithm checks each element (except first and last) against its neighbors:
-
Simple Peak: If
arr[i] > arr[i-1]andarr[i] > arr[i+1], it's a peak - Plateau Handling: When consecutive equal values are found, we check if they form a peak by comparing with the element after the plateau
- Boundary Exclusion: First and last elements can't be peaks since they don't have neighbors on both sides
Example with Different Array
const arr2 = [1, 3, 3, 3, 2, 5, 1, 4];
console.log("Array:", arr2);
console.log("Peaks:", findMaxima(arr2));
Array: [1, 3, 3, 3, 2, 5, 1, 4]
Peaks: { maximas: [ 3, 5 ], positions: [ 1, 5 ] }
Conclusion
This algorithm efficiently finds all peaks in an array by comparing each element with its neighbors, handling both simple peaks and plateaus. The time complexity is O(n) and space complexity is O(k) where k is the number of peaks found.
