mediumMonotonic StackStack

132 Pattern

mediumTime: O(n)Space: O(n)

Recognize the pattern

find subsequence i < j < k with nums[i] < nums[k] < nums[j]132 patterntrack candidates

Brute force idea

The naive version of 132 Pattern sounds like this: Check all triplets. Triple nested loop. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

Better approach

The deeper shift in 132 Pattern is this: Scan right to left with a monotonic decreasing stack. Track the largest 'popped' value as the candidate for nums[k] (the '2' in 132). If any element is smaller than this candidate, return true. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Key invariant

At the center of 132 Pattern is one steady idea: The stack tracks candidates for the '3' (largest). Popped values become candidates for the '2' (second largest). If we find a '1' (smaller than the '2' candidate), the 132 pattern exists. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

The trap in 132 Pattern usually looks like this: Searching left-to-right — the right-to-left approach with stack is much cleaner because it naturally identifies the 3-2 pair and then checks for the 1. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Stack Pattern