-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0496-next-greater-element-i.js
More file actions
29 lines (25 loc) · 951 Bytes
/
0496-next-greater-element-i.js
File metadata and controls
29 lines (25 loc) · 951 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Next Greater Element I
* Time Complexity: O(N + M)
* Space Complexity: O(M)
*/
var nextGreaterElement = function (nums1, nums2) {
const nextGreaterMappings = new Map();
const decreasingStack = [];
for (let currentIterator = 0; currentIterator < nums2.length; currentIterator++) {
let currentElement = nums2[currentIterator];
while (decreasingStack.length > 0 && currentElement > decreasingStack[decreasingStack.length - 1]) {
let poppedValue = decreasingStack.pop();
nextGreaterMappings.set(poppedValue, currentElement);
}
decreasingStack.push(currentElement);
}
while (decreasingStack.length > 0) {
let remainingElement = decreasingStack.pop();
nextGreaterMappings.set(remainingElement, -1);
}
const finalAnswer = nums1.map(queryNumber => {
return nextGreaterMappings.get(queryNumber);
});
return finalAnswer;
};