FAANG · LeetCode #496
Next Greater Element I — three-stage drill
1The ProblemEasy
Next Greater Element I
For each value in nums1, find its next greater element in nums2.
Examples
nums1=[4,1,2], nums2=[1,3,4,2]→ [-1,3,-1]nums1=[2,4], nums2=[1,2,3,4]→ [3,-1]
constraintnums1 is a subset of nums2; values are distinct.
2The PatternTIME O(n) · SPACE O(n)
Monotonic Stack
A stack kept sorted; each new value pops everything it resolves, so each element is pushed and popped once — O(n).
Problems using this pattern
3The SolutionRESULT → [-1, 3, -1]
Step through it
1 → push (nothing bigger yet)
Step 1 / 10
Arrow keys to navigate · escape to reset