132 Pattern (LeetCode 456): Solution and Explanation

Medium
Array
Stack
Monotonic Stack
Binary Search
Ordered Set

Decide whether nums contains indices i < j < k with nums[i] < nums[k] < nums[j]: a small value, then a large one, then one in between.

Intuition

Name the three roles by the digits: the 1 comes first and is the smallest, the 3 is in the middle and is the largest, and the 2 comes last and sits between them.

Checking every triple is O(n^3). The useful observation is that for a fixed pair (3, 2) with the 3 to the left of the 2, we only need some value to the left of the 3 that is smaller than the 2. So we want the 2 to be as large as possible.

Scan from right to left and keep a stack of values seen so far. When the current value is bigger than the top of the stack, that top has a bigger value to its left, so it is a valid 2 with the current value as its 3. Pop it and remember it in third. Popping all smaller tops keeps the largest such 2.

Every later value (further left) that is smaller than third is a valid 1, because its 3 and 2 are already to its right. That check is a single comparison per element.

Approach: Monotonic stack scanned from the right

  1. Set third = -infinity and start with an empty stack.
  2. For i from n - 1 down to 0, return true if nums[i] < third.
  3. While the stack top is smaller than nums[i], pop it and store it in third.
  4. Push nums[i] onto the stack.
  5. If the loop finishes, return false.

Step-by-step example

nums = [1,2,3,4]
  1. i = 3: third is -inf, nothing to pop. Push 4. Stack: [4].
  2. i = 2: 3 is not below third. The top 4 is not smaller than 3, so nothing pops. Push 3. Stack: [4,3].
  3. i = 1: push 2. Stack: [4,3,2]. i = 0: push 1. Stack: [4,3,2,1].
  4. No value ever had a smaller value to its right, so third never left -inf and no 1 could be found.
  5. Return false.

Code: Python, Java, C++

1class Solution:
2    def find132pattern(self, nums: List[int]) -> bool:
3        stack = []
4        third = float('-inf')
5        for i in range(len(nums) - 1, -1, -1):
6            if nums[i] < third:
7                return True
8            while stack and stack[-1] < nums[i]:
9                third = stack.pop()
10            stack.append(nums[i])
11        return False
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each index is pushed once and popped at most once, and each step does one comparison against third.

Space

O(n)

The stack can hold every element, for example when the array is strictly increasing from left to right.

Other approaches

Prefix minimum with a sorted structure (time O(n log n), space O(n))

For each j, the best 1 is the minimum of nums[0..j-1]. Keep the values to the right of j in a sorted multiset and look for the smallest value greater than that minimum, then check it is below nums[j].

Brute force with a running minimum (time O(n^2), space O(1))

Fix j, take the minimum to its left, and scan to its right for a value strictly between them. Simple but quadratic.

Common mistakes

  • Scanning left to right with the same stack logic. The pop rule only proves a valid (3, 2) pair when the 3 is to the left of the 2, which is why the scan runs right to left.
  • Using <= in the pop condition or the check. All three comparisons are strict, so equal values never form a pattern.
  • Starting third at 0 or at Integer.MIN_VALUE stored in an int. Values can be negative and as low as -10^9, so use negative infinity or a 64-bit minimum.
  • Resetting third after a pop. It only ever grows, and a larger third is never worse.

Frequently asked questions

Why is it safe to keep only the largest third?

Any 1 that works for a smaller 2 also works for a larger valid 2, since the test is just nums[i] < third. Keeping the largest valid 2 can only find more patterns, never fewer.

Why does the stack stay decreasing from bottom to top?

Before pushing nums[i] we pop every top smaller than it. So whatever is left below it is at least as large, and the stack reads from largest at the bottom to smallest at the top.

Are the stack values always greater than third?

Yes. third is set to a popped value, and the value that caused the pop is pushed right after, so it is larger. Values pushed later only pop smaller tops. This is why a single comparison against third is enough.

Can the answer be found without the stack?

Yes, with a prefix minimum and a sorted set in O(n log n), or a quadratic scan. The stack version is the standard O(n) solution and the one interviewers expect.