LeetCode 496 Next Greater Element I - Implementation

The approach

Monotonic decreasing stack. Pop when current is greater, store mapping.

function nextGreaterElement(nums1, nums2): nextGreater = {} stack = [] for num in nums2: while stack and num > stack[-1]: nextGreater[stack.pop()] = num stack.push(num) result = [] for num in nums1: result.append(nextGreater.get(num, -1)) return result

O(n+m)O(n + m) time, O(n)O(n) space.