Skip to content

visual walkthrough

132 Pattern

MediumMonotonic StackReported at: Amazon

Scans from the right while tracking a candidate value; a tricky monotonic stack.

Solve on LeetCode

The idea

A 132 pattern is "small, big, middle": positions i < j < k with nums[i] < nums[k] < nums[j].

Scan from the right with a stack. A number that pops smaller values is a valid "3" for them, and the largest popped value is the best "2". Any later (further left) number below that "2" completes the pattern.

Complexity

approachtimespace
Fix the middleO(n²)O(1)
Monotonic stack from the rightO(n)O(n)

More walkthroughs