132 Pattern
Decide whether an array has a low value, then a higher one, then one in between, using one pass and a stack.
Given an array of integers numstruefalsenums[i]nums[j]nums[k]i < j < knums[i] < nums[k] < nums[j]
Example 1
Output: false
Example 2
Output: true
Explanation: 1, 4, 2 is a 132 pattern.
Example 3
Output: true
Explanation: -1, 3, 2 and -1, 3, 0 and -1, 2, 0 are all 132 patterns.
The Idea
Think of the numbers as a walk over hills: a low point, then a climb to a peak, then a drop that stays above the low point. In Example 2, [3, 1, 4, 2][1, 2, 3, 4]
To talk about the three values, call them by their place in 132. The "1" is the low value and comes first. The "3" is the peak and comes next. The "2" comes last and lies between the other two. We could try every choice of three positions, but that is slow on long arrays. Is there a way to look at each number only once?
Suppose we already had a "3" and, later, a "2", say 5 and then 4. Then any earlier number below 4 would finish the pattern. A bigger "2" lets more numbers count as the "1". So if we read the array from the right, we only need to remember one thing: the largest "2" found so far that has a bigger "3" before it. Call that value the best "2" so far; the code keeps it in a variable named twotwo
How do we find those "2" values while reading from the right? Keep the numbers read so far in a stack, a pile where the last value put on is the first one taken off. When a new number is bigger than the value on top, it is a "3" for that value, so we take the value off and it becomes a "2". Look at the picture below, which reads [3, 5, 0, 3, 4]
In the first three rows, 4, 3 and 0 go onto the stack one by one. Each is smaller than the value on top, or finds the stack empty, so nothing is popped. The row labelled "read 5: pops 0, 3, 4" is where things happen. 5 is bigger than all three, so it is a "3" for each of them. They come off the stack smallest first, and the last one, 4, is the largest, so the best "2" so far, in the last column, becomes 4. In the last row, the 3 at the start of the array is less than 4, and the pattern is 3, then 5, then 4.
Notice that the stack always holds its values in decreasing order from bottom to top: a new value first removes every smaller value on top, then goes on. A stack kept in order like this is called a monotonic stack.
Solution Approach
Turning that idea into code means looking at why trying every three positions is slow, then settling three things: why to read from the right, what the stack and two
Trying every three positions
Why not test every choice of three positions? That needs three nested loops. For 1,000 numbers there are about 166 million choices, and for an array of n numbers the work grows with n³, written O(n³). A single pass from the right with a stack looks at each number only once.
Reading from the right
Why go backwards? The "1" comes first, and it is the last piece we need: once a "3" and a "2" are known, a "1" only has to be smaller than the "2". Reading from the right, the numbers already read are exactly the ones after the current position, which is where its "3" and "2" must be.
What the stack and two hold
What exactly sits on the stack? Numbers that have been read but have not yet met a bigger number to their left. When a new number pops one off, that popped value has a "3" before it, so it is a valid "2". The stack is decreasing from bottom to top, so values come off smallest first and the last one popped is the largest.
What should twoInteger.MIN_VALUEinttwo
Is a popped value ever needed again? No. two
Equal values
What if the new number equals the value on top of the stack? It must not pop it. The pattern needs the "3" to be strictly bigger than the "2", so the loop pops only while the top is smaller than the new number.
Java Solution
The method find132pattern
- First, create an empty
. It is anstack , a Java class that works as a stack withArrayDeque ,push andpop , which looks at the top value without removing it. Then setpeek totwo , meaning no "2" yet.Integer.MIN_VALUE - Read the array from right to left with a loop over
, from the last position down to 0.i - If
is smaller thannums[i] , it is the "1", so returntwo .true - Otherwise, inside a second loop, pop every value on top of
that is smaller thanstack , and store each one innums[i] . The last one popped is the largest.two - Push
ontonums[i] , since it may be the "3" for a later number.stack - If the loop reaches the start of the array without finding a "1", return
.false
The main
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
public class Find132Pattern {
public static boolean find132pattern(int[] nums) {
Deque<Integer> stack = new ArrayDeque<>(); // values still waiting for a bigger "3"
int two = Integer.MIN_VALUE; // largest "2" found so far; none yet
for (int i = nums.length - 1; i >= 0; i--) {
if (nums[i] < two) {
return true; // nums[i] is the "1"
}
while (!stack.isEmpty() && stack.peek() < nums[i]) {
two = stack.pop(); // nums[i] is a "3" for the popped value
}
stack.push(nums[i]);
}
return false;
}
public static void main(String[] args) {
int[][] tests = {
{1, 2, 3, 4},
{3, 1, 4, 2},
{-1, 3, 2, 0},
{1, 2, 2},
{3, 5, 0, 3, 4},
{5}
};
for (int[] nums : tests) {
System.out.println(Arrays.toString(nums) + " -> " + find132pattern(nums));
}
}
}
Running it prints:
[1, 2, 3, 4] -> false
[3, 1, 4, 2] -> true
[-1, 3, 2, 0] -> true
[1, 2, 2] -> false
[3, 5, 0, 3, 4] -> true
[5] -> false
The first line is falsetwotwo
Look at the line for [1, 2, 2]falsestack.peek() <= nums[i]twotrue[1, 2, 2][1, 3, 3]
The line for [3, 5, 0, 3, 4]false
The original implementation,
Complexity
The work is one pass over the array, plus the pushes and pops on the stack.
- Time: O(n), because the outer loop reads each of the n numbers once, and each number is pushed once and popped at most once, so all the pops together add up to at most n.
- Space: O(n) for the stack. On an array that only climbs, such as
, nothing is ever popped, so all n numbers end up on the stack.[1, 2, 3, 4]
For more problems that keep a stack in order, see the