mediumMonotonic StackStack

132 Pattern

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

Signals to notice

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

Brute force first

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.

The key insight

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.

What must stay true

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.

Easy way to go wrong

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