Coding Interview Patterns132 Pattern
MediumMonotonic Stack
132 Pattern
Explanation & Solution
Description
Given an array of n integers nums, return true if there exists a 132 pattern in the array.
A 132 pattern is a subsequence of three integers nums[i], nums[j], nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].
Input:nums = [1, 2, 3, 4]
0
1
1
2
2
3
3
4
Output: false
Explanation: There is no 132 pattern in the sequence.
Constraints
n == nums.length1 <= n <= 2 * 10^5-10^9 <= nums[i] <= 10^9
Approach
Monotonic Stack pattern
1. Handle Edge Cases
- If the array has fewer than 3 elements, return
falseimmediately since a 132 pattern requires at least three values.
2. Initialize a Monotonic Stack and a "Third" Variable
- Create an empty stack that will maintain a decreasing order from bottom to top.
- Initialize
thirdto-Infinity. This variable tracks the best candidate for the "2" in the 132 pattern (i.e.,nums[k], the middle value that is less thannums[j]but greater thannums[i]).
3. Iterate from Right to Left
- Traverse the array from the last element to the first.
- For each element
nums[i], check if it is less thanthird. If so, we have found a valid "1" — an element smaller than both the "3" (which was on the stack) and the "2" (third). Returntrue.
4. Maintain the Stack
- While the stack is not empty and the top of the stack is less than
nums[i], pop elements from the stack. - Each popped element becomes the new
third, because it was smaller than the currentnums[i](which acts as the "3" in the pattern), making it a valid "2" candidate. - Push
nums[i]onto the stack.
5. Return False if No Pattern Found
- If the entire array is traversed without finding a valid "1" element, return
false.
Key Insight
- By iterating from right to left, we use a monotonic stack to efficiently track the largest possible "2" value (
third) that is smaller than some "3" value already seen. The moment we encounter a "1" value smaller thanthird, the 132 pattern is confirmed.
Time
O(n)each element is pushed and popped from the stack at most once.Space
O(n)the stack can hold up to n elements in the worst case.Visualization
Input:
[1, 2, 3, 4]
—
No animation available
Left (L)Right (R)ConvergedDone
0 steps