132 Pattern (LeetCode 456): Solution and Explanation
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
- Set
third = -infinityand start with an empty stack. - For
ifromn - 1down to0, return true ifnums[i] < third. - While the stack top is smaller than
nums[i], pop it and store it inthird. - Push
nums[i]onto the stack. - If the loop finishes, return false.
Step-by-step example
nums = [1,2,3,4]
- i = 3: third is -inf, nothing to pop. Push 4. Stack: [4].
- i = 2: 3 is not below third. The top 4 is not smaller than 3, so nothing pops. Push 3. Stack: [4,3].
- i = 1: push 2. Stack: [4,3,2]. i = 0: push 1. Stack: [4,3,2,1].
- No value ever had a smaller value to its right, so third never left -inf and no 1 could be found.
- 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 False1class Solution {
2 public boolean find132pattern(int[] nums) {
3 Deque<Integer> stack = new ArrayDeque<>();
4 long third = Long.MIN_VALUE;
5 for (int i = nums.length - 1; i >= 0; i--) {
6 if (nums[i] < third) {
7 return true;
8 }
9 while (!stack.isEmpty() && stack.peek() < nums[i]) {
10 third = stack.pop();
11 }
12 stack.push(nums[i]);
13 }
14 return false;
15 }
16}1class Solution {
2public:
3 bool find132pattern(vector<int>& nums) {
4 vector<int> st;
5 long long third = LLONG_MIN;
6 for (int i = (int) nums.size() - 1; i >= 0; i--) {
7 if (nums[i] < third) {
8 return true;
9 }
10 while (!st.empty() && st.back() < nums[i]) {
11 third = st.back();
12 st.pop_back();
13 }
14 st.push_back(nums[i]);
15 }
16 return false;
17 }
18};Time and space complexity
O(n)
Each index is pushed once and popped at most once, and each step does one comparison against third.
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
thirdat 0 or atInteger.MIN_VALUEstored in an int. Values can be negative and as low as -10^9, so use negative infinity or a 64-bit minimum. - Resetting
thirdafter 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.