132 Pattern

MediumMonotonic Stack🧩 Monotonic StackLeetCode #456 ↗Updated

Problem

You are given an integer array nums. Decide whether it hides three positions i < j < k whose values are shaped like the digits “1-3-2”: nums[i] < nums[k] < nums[j]. The three positions do not have to be adjacent. Return true if such a triple exists.
Inputnums = [1,2,3,4]Outputfalse
Inputnums = [3,1,4,2]Outputtrue (1, 4, 2)
Inputnums = [-1,3,2,0]Outputtrue (-1, 3, 2)

1 ≤ n ≤ 2·105  ·  -109 ≤ nums[i] ≤ 109

Try it yourself

Java
class Solution {
    public boolean find132pattern(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Scan from the right and treat each value as the “3”. Every smaller value it pops off a decreasing stack is a valid “2” for it; remember the largest popped value. If any later (further-left) number is below that, it is the “1”.
PatternMonotonic Stack

Instinct Each element needs its nearest bigger or smaller neighbour (next warmer day, span, widest bar) - keep a sorted stack of waiting indices.

Memory hack Tall people block the view - a newcomer kicks out everyone shorter waiting behind, and each kicked-out person just found their answer.

Open the Monotonic Stack guide →

Approaches

Brute ForceTry Every Triple

Time O(n3)Space O(1)

Enumerate all index triples i < j < k and test the inequality directly. It is the definition turned into code, so it is obviously correct and serves as a reference.

Java
public boolean find132pattern(int[] nums) {
    int n = nums.length;
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            for (int k = j + 1; k < n; k++) {
                if (nums[i] < nums[k] && nums[k] < nums[j]) return true;
            }
        }
    }
    return false;
}

Correct but cubic — hopeless beyond a few hundred elements.

At a glance

LevelApproachTimeSpace
Brute ForceTry Every TripleO(n3)O(1)
BetterFix the Middle, Use the Prefix MinimumO(n2)O(1)
OptimalRight-to-Left Decreasing StackO(n)O(n)
Common pitfalls
  • Using non-strict comparisons — equal values never form a 132 pattern.
  • Scanning left-to-right with a stack and losing track of which value is the “1”.
  • Using Integer.MIN_VALUE as the sentinel when inputs may equal it — a long is safer.
Interview tips
  • Name the roles (“1”, “3”, “2”) before coding; it keeps the logic clear.
  • Bridge from O(n2): the prefix-minimum trick shows you think about greedy choices.
  • Explain why third never decreases — that is the correctness argument.
Pattern
Monotonic stack → when each element needs the nearest/best smaller or larger value on one side.
My notes saved in this browser