KatInterview

456. 132 Pattern

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to determine if an array of integers nums contains a "132 pattern". A 132 pattern is a subsequence of three integers nums[i], nums[j], nums[k] that satisfy two conditions:

Solution

132 Pattern in Python

class Solution:
    def find132pattern(self, nums: List[int]) -> bool:
        n = len(nums)
        if n < 3:
            return False

        # Stack to store candidates for s3 (the '3' in 132)
        s3_candidates = []
        
        # s2_val will store the maximum candidate for s2 (the '2' in 132)
        s2_val = float('-inf')

        # Iterate from right to left
        # The current number nums[i] is a candidate for s1 (the '1' in 132)
        for i in range(n - 1, -1, -1):
            # Check if we found a '1' (nums[i]) that is smaller than our '2' (s2_val)
            if nums[i] < s2_val:
                return True
            
            # nums[i] is a potential s3. We find the best s2 for it from the stack.
            # While stack has elements and current number is larger than stack top,
            # it means we have found a (s3, s2) pair: (nums[i], s3_candidates[-1]).
            while s3_candidates and nums[i] > s3_candidates[-1]:
                # Update s2_val with a new, larger candidate.
                s2_val = s3_candidates.pop()
            
            # Push current number as a potential s3 for elements to its left.
            s3_candidates.append(nums[i])
            
        return False

132 Pattern in Java

class Solution {
    public boolean find132pattern(int[] nums) {
        int n = nums.length;
        if (n < 3) {
            return false;
        }

        // Stack to store candidates for s3 (the '3' in 132)
        Stack<Integer> s3_candidates = new Stack<>();
        
        // s2_val will store the maximum candidate for s2 (the '2' in 132)
        int s2_val = Integer.MIN_VALUE;

        // Iterate from right to left
        // The current number nums[i] is a candidate for s1 (the '1' in 132)
        for (int i = n - 1; i >= 0; i--) {
            // Check if we found a '1' (nums[i]) that is smaller than our '2' (s2_val)
            if (nums[i] < s2_val) {
                return true;
            }

            // nums[i] is a potential s3. We find the best s2 for it from the stack.
            // While stack has elements and current number is larger than stack top,
            // it means we have found a (s3, s2) pair: (nums[i], stack.peek()).
            while (!s3_candidates.isEmpty() && nums[i] > s3_candidates.peek()) {
                // Update s2_val with a new, larger candidate.
                s2_val = s3_candidates.pop();
            }

            // Push current number as a potential s3 for elements to its left.
            s3_candidates.push(nums[i]);
        }

        return false;
    }
}

132 Pattern in C++

class Solution {
public:
    bool find132pattern(vector<int>& nums) {
        int n = nums.size();
        if (n < 3) {
            return false;
        }

        // Stack to store candidates for s3 (the '3' in 132)
        stack<int> s3_candidates;
        
        // s2_val will store the maximum candidate for s2 (the '2' in 132)
        int s2_val = INT_MIN;

        // Iterate from right to left
        // The current number nums[i] is a candidate for s1 (the '1' in 132)
        for (int i = n - 1; i >= 0; --i) {
            // Check if we found a '1' (nums[i]) that is smaller than our '2' (s2_val)
            if (nums[i] < s2_val) {
                return true;
            }

            // nums[i] is a potential s3. We find the best s2 for it from the stack.
            // While stack has elements and current number is larger than stack top,
            // it means we have found a (s3, s2) pair: (nums[i], stack.top()).
            while (!s3_candidates.empty() && nums[i] > s3_candidates.top()) {
                // Update s2_val with a new, larger candidate.
                s2_val = s3_candidates.top();
                s3_candidates.pop();
            }
            
            // Push current number as a potential s3 for elements to its left.
            s3_candidates.push(nums[i]);
        }

        return false;
    }
};

132 Pattern in TypeScript

function find132pattern(nums: number[]): boolean {
    const n = nums.length;
    if (n < 3) {
        return false;
    }

    // Stack to store candidates for s3 (the '3' in 132)
    const s3_candidates: number[] = [];

    // s2_val will store the maximum candidate for s2 (the '2' in 132)
    let s2_val = -Infinity;

    // Iterate from right to left
    // The current number nums[i] is a candidate for s1 (the '1' in 132)
    for (let i = n - 1; i >= 0; i--) {
        // Check if we found a '1' (nums[i]) that is smaller than our '2' (s2_val)
        if (nums[i] < s2_val) {
            return true;
        }

        // nums[i] is a potential s3. We find the best s2 for it from the stack.
        // While stack has elements and current number is larger than stack top,
        // it means we have found a (s3, s2) pair: (nums[i], stack top).
        while (s3_candidates.length > 0 && nums[i] > s3_candidates[s3_candidates.length - 1]) {
            // Update s2_val with a new, larger candidate.
            s2_val = s3_candidates.pop()!;
        }

        // Push current number as a potential s3 for elements to its left.
        s3_candidates.push(nums[i]);
    }

    return false;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.