Skip to content

Commit 1ce1778

Browse files
committed
update: find next greater for each element in an array
1 parent dbd8670 commit 1ce1778

File tree

1 file changed

+46
-0
lines changed
  • src/_Problems_/next-greater-element

1 file changed

+46
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
You must implement the nextGreaterElement() function.
3+
For each element in an array, it finds the next greater element in that array.
4+
To keep it simple, the next greater element for the last or maximum value in the array is -1.
5+
6+
Input: [4, 6, 3, 2, 8, 1]
7+
Output: {6, 8, 8, 8, -1, -1}
8+
*/
9+
10+
const Stack = require('../../_DataStructures_/Stack');
11+
12+
function nextGreaterElement(arr) {
13+
if (!Array.isArray(arr)) {
14+
throw new Error('Invalid Argument');
15+
}
16+
17+
const s1 = new Stack();
18+
const nextGreater = [];
19+
20+
for (let i = arr.length - 1; i >= 0; i -= 1) {
21+
if (s1.peek()) {
22+
let top = s1.peek();
23+
while (top <= arr[i]) {
24+
// if the stack is empty, break the while loop
25+
if (!s1.peek()) break;
26+
// pop the elements
27+
s1.pop();
28+
// get the new top
29+
top = s1.peek();
30+
}
31+
}
32+
33+
if (s1.peek()) {
34+
nextGreater[i] = s1.peek();
35+
} else {
36+
nextGreater[i] = -1;
37+
}
38+
39+
// push the element into the stack
40+
s1.push(arr[i]);
41+
}
42+
return nextGreater;
43+
}
44+
45+
// eslint-disable-next-line no-console
46+
console.log(nextGreaterElement([4, 6, 3, 2, 8, 1]));

0 commit comments

Comments
 (0)