Problem
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.

next greater = first taller bar to the right →10314223−1−1ask for nums1 = [4, 1, 2]return[-1, 3, -1]
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).

a bigger value pops every smaller one, then is pushed3011421354scan›stack — kept decreasingbottom3top is always the smallest — so it pops firststack empty → push 3
Problems using this pattern
3The SolutionRESULT → [-1, 3, -1]

Step through it

phase 1 — build next-greater map (stack over nums2)nums210314223x›stack ↓bottom1value → next greaternext = {}
1 → push (nothing bigger yet)
Step 1 / 10
Arrow keys to navigate · escape to reset

All problems by pattern

Backtracking

Recursive Descent