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 nums, return true if it contains a 132 pattern, and false otherwise. A 132 pattern is three values nums[i], nums[j] and nums[k], at positions i < j < k, with nums[i] < nums[k] < nums[j]. In words: a low value, later a higher one, and after that a value in between, like the digits of 132. The three values do not have to sit next to each other.

Example 1
Input: nums = [1, 2, 3, 4]
Output: false
Example 2
Input: nums = [3, 1, 4, 2]
Output: true
Explanation: 1, 4, 2 is a 132 pattern.
Example 3
Input: nums = [-1, 3, 2, 0]
Output: true
Explanation: -1, 3, 2 and -1, 3, 0 and -1, 2, 0 are all 132 patterns.
Solution

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], the walk dips to 1, climbs to 4 and drops back to 2. Since 2 is still above 1, the shape is there. Example 1, [1, 2, 3, 4], only climbs, so there is never a drop after a peak.

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 two. Any new number smaller than two is a "1", and we are done.

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] from the right.

Reading 3, 5, 0, 3, 4 from the right. 4, 3 and 0 go onto the stack. Reading 5 pops 0, 3 and 4, so the best

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 hold, and how to treat equal values.

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 two start as, before any "2" exists? Integer.MIN_VALUE, the smallest value an int can hold. No number is smaller than it, so the test "smaller than two" cannot succeed until a real "2" has been popped.

Is a popped value ever needed again? No. two already holds a value at least as large, and a larger "2" is always at least as good for finding a "1".

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 works in these steps:

  1. First, create an empty stack. It is an ArrayDeque, a Java class that works as a stack with push, pop and peek, which looks at the top value without removing it. Then set two to Integer.MIN_VALUE, meaning no "2" yet.
  2. Read the array from right to left with a loop over i, from the last position down to 0.
  3. If nums[i] is smaller than two, it is the "1", so return true.
  4. Otherwise, inside a second loop, pop every value on top of stack that is smaller than nums[i], and store each one in two. The last one popped is the largest.
  5. Push nums[i] onto stack, since it may be the "3" for a later number.
  6. If the loop reaches the start of the array without finding a "1", return false.

The main method runs the three examples, an array with two equal values at the end, the array from the picture, and an array of one number.

Java
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:

Output
[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 false: read from the right, 4 finds the stack empty, and 3, 2 and 1 are each smaller than the value on top when they arrive, so nothing is ever popped and two never changes. In the third line, two becomes 0 when 2 is read, then 2 when 3 is read, and -1 is below it.

Look at the line for [1, 2, 2]. It prints false, which is right, because 2, 2 cannot be a "3" and a "2". With stack.peek() <= nums[i] in the inner loop, the first 2 would pop the second one, two would become 2, and 1 would complete a false match. A test run of that version returns true for [1, 2, 2] and for [1, 3, 3].

The line for [3, 5, 0, 3, 4] is the picture's array. Its "1" is 3, not the smallest number 0, because 0 comes after the 5. The last line is false, since one number cannot make three.

The original implementation, Find132Pattern.java, is on GitHub.

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 [1, 2, 3, 4], nothing is ever popped, so all n numbers end up on the stack.

For more problems that keep a stack in order, see the monotonic stack introduction.