Next Greater Element I Visualizer & Step-by-Step Algorithm Solution

Find the next greater element for each number in nums1 within nums2 using a monotonic stack and hash map.

Category: stack | Difficulty: Easy

Tags: Monotonic Stack, Hash Map, Array

Next Greater Element I

nums2 (Search Array)
1
0
3
1
4
2
2
3
nums1 (Query Array)
4
0
1
1
2
2
ans (Result Array)
0
1
2
Next Greater Elements Map
(Empty Map)
Push / Pop (Top)
(Empty Stack)
Monotonic Stack
100%
state
stack.length0
Initialization
1/19
Explanation

Initialize empty nextGreater map.

Source Code
1function nextGreaterElement(nums1, nums2) {
2 const nextGreater = new Map();
3 const stack = [];
4 for (let i = 0; i < nums2.length; i++) {
5 const num = nums2[i];
6 while (stack.length && stack[stack.length - 1] < num) {
7 const popped = stack.pop();
8 nextGreater.set(popped, num);
9 }
10 stack.push(num);
11 }
12 const ans = [];
13 for (let j = 0; j < nums1.length; j++) {
14 ans.push(nextGreater.get(nums1[j]) ?? -1);
15 }
16 return ans;
17}