132 Pattern solution explained
132 Pattern asks whether some three positions i < j < k hold values that rise then fall to the middle: nums[i] < nums[k] < nums[j]. Scan from the right with a stack: when a value pops smaller values off the stack, it can serve as the "3" for them, so remember the largest popped value as the best "2". If any later-scanned (further left) value is below that "2", the pattern exists. Each value is pushed and popped at most once, so it is O(n).
By Evin JohnPublished 7 min read
The problem in plain words
Given a list of integers, decide whether you can pick three of them, keeping their original order, so that the first is the smallest, the second is the largest, and the third lies strictly between them. The name comes from the relative sizes: 1, then 3, then 2. The picks do not have to be next to each other.
| Array | Pattern? | One witness (1, 3, 2) |
|---|---|---|
[3, 5, 0, 3, 4] | Yes | 3, 5, 4 |
[2, 4, 3] | Yes | 2, 4, 3 |
[5, 1, 8, 7] | Yes | 1, 8, 7 (or 5, 8, 7) |
[1, 2, 3, 4] | No | Always rising |
[2, 9, 9, 2] | No | The last 2 equals the first, and "between" is strict |
[6, 5, 5, 4] | No | Never rises |
Why it is a favorite
There is a natural ladder of solutions: cubic, quadratic, then linear with a stack. Interviewers can stop at whichever rung fits the time left, and the last rung tests whether you understand a stack well enough to use what it pops, not only what it holds. Getting the strict inequalities right is the other thing they watch.
Step 1: three nested loops
def has_132_slow(nums):
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
if nums[i] < nums[k] < nums[j]:
return True
return FalseStep 2: the best "1" for each "3"
For a fixed j, the best choice of i is simply the smallest value before j: a smaller "1" leaves more room for the "2". Track that running minimum, then scan k to the right of j looking for a value strictly between it and nums[j].
def has_132_quadratic(nums):
lowest = float("inf") # smallest value before j: the best "1"
for j in range(len(nums)):
lowest = min(lowest, nums[j])
for k in range(j + 1, len(nums)):
if lowest < nums[k] < nums[j]:
return True
return FalseIncluding nums[j] in the minimum is harmless: if the minimum is nums[j] itself, no k can satisfy lowest < nums[k] < nums[j], so no false positive appears.
Step 3: scan from the right with a stack
Turn the search around. Walk from the last element to the first. Keep a stack of values seen so far (to the right of the current position) and a variable third: the largest value that we already know has a bigger value to its left, which makes it a valid "2" for a "3" we have passed. At each new value:
- Check for a "1"If the value is less than
third, it sits to the left of a "3" and a "2" with 1 < 2 < 3. Return true. - Act as a "3"While the stack's top is smaller than the value, pop it and set
thirdto it. Each popped value has this bigger value to its left, so it is a valid "2". - Push the valueIt may become a "3" or a "2" for values further left.
Why is it enough to remember one value? Two facts. First, third never goes down: every value that passes the check is at least third, so everything pushed since the last pop is at least third, and any later pop can only set it to something as large or larger. Second, a larger "2" is always at least as good, because its "3" lies between it and the current position either way, and a bigger "2" makes the "1" check easier. So keeping the largest known "2" loses nothing.
def has_132(nums):
third = float("-inf") # best "2" so far: a value with something bigger to its left
stack = [] # candidates for "3", scanned from the right
for value in reversed(nums):
if value < third: # value can be the "1"
return True
while stack and stack[-1] < value:
third = stack.pop() # value is a "3" for everything it pops
stack.append(value)
return Falsefunction has132(nums) {
let third = -Infinity;
const stack = [];
for (let i = nums.length - 1; i >= 0; i--) {
const value = nums[i];
if (value < third) return true;
while (stack.length && stack[stack.length - 1] < value) third = stack.pop();
stack.push(value);
}
return false;
}Trace on the first example
[3, 5, 0, 3, 4] from the right. Value 4: push. Value 3: not below third (still minus infinity), 4 is not smaller, push. Value 0: push. Value 5: pops 0, then 3, then 4, so third becomes 4; push 5. Value 3: 3 is below 4, so return true. The witness is 3 (the "1"), 5 (the "3") and 4 (the "2").
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Every triple | O(n³) | O(1) |
| Running minimum as the "1" | O(n²) | O(1) |
| Right-to-left stack | O(n) | O(n) |
Edge cases
- Fewer than three elements: false.
- Equal values: the inequalities are strict, so
[2, 9, 9, 2]and[1, 3, 3]have no pattern. Pop only while the top is strictly smaller, and check value < third strictly. - Negative numbers and very large values: start
thirdat minus infinity (or the smallest possible integer in a typed language) rather than 0 or -1. - Strictly increasing or strictly decreasing arrays: false.
Mistakes to avoid
- Scanning left to right with the same stack logic; the roles of "3" and "2" only line up from the right.
- Setting
thirdto the current value instead of the popped value. - Using
<=in the pop condition, which can make an equal value look like a valid "2". - Initializing
thirdto 0, which breaks on arrays of negative numbers.
How to explain it out loud
Fictional example
- Candidate
- Brute force checks every triple, cubic. If I fix the middle, the best first element is the smallest one before it, which gets me to quadratic.
- Candidate
- For linear, I'll scan from the right with a stack. When a value pops smaller values, it's a '3' for each of them, so the largest popped value is my best '2'.
- Candidate
- If I then meet anything smaller than that '2', it's the '1' and I'm done. Each value is pushed and popped at most once.
Related problems
Next Greater Element II is the same kind of stack used to answer a query per element. Max Chunks To Make Sorted keeps a stack of maxima and merges them, and Sum of Subarray Minimums counts with stacks on both sides. See the coding problems hub for more.
Practicing it with Natively
Natively works on Mac and Windows; in a practice session it can read the 132 prompt from a screenshot and quiz you on why the largest popped value is the one to keep, or check your strict inequalities. The transcript and notes of your mock stay in its history so you can hear how you climbed from cubic to linear. See the AI interview assistant page.
Questions people ask
How do you solve the 132 Pattern problem?
Scan from right to left with a stack. When a value pops smaller values, record the largest popped one as the best middle value. If a later value is smaller than that, you have found the pattern.
What is the time complexity of the 132 Pattern stack solution?
O(n) time and O(n) space, because every value is pushed once and popped at most once.
Is there an O(n²) solution for 132 Pattern?
Yes. For each middle index, use the smallest value before it as the first element and scan to the right for a value strictly between the two.
Why scan from the right in 132 Pattern?
From the right, a value that pops smaller values is a valid high point for them, so the popped values become candidates for the final element. Then any value further left below that candidate completes the pattern.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
