LeetCode 456: 132 Pattern Solution

Master LeetCode problem 456 (132 Pattern), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation:

To solve this problem, we can iterate through the array elements from right to left. We maintain a stack to keep track of potential candidates for the middle element (num[j]) and the smallest element on the left (num[i]). As we iterate through the array, we check if the current element is greater than the element at the top of the stack. If it is, we pop elements from the stack until we find a smaller element. This smaller element will be our num[i]. If we find a num[k] (element at the top of the stack) that is less than the current element, we have found a 132 pattern.

Time Complexity:

The time complexity of this solution is O(n), where n is the number of elements in the input array.

Space Complexity:

The space complexity of this solution is O(n) due to the stack used.

: :

Solution Code

class Solution {
    public boolean find132pattern(int[] nums) {
        Stack<Integer> stack = new Stack<>();
        int n = nums.length;
        int third = Integer.MIN_VALUE;

        for (int i = n - 1; i >= 0; i) {
            if (nums[i] < third) {
                return true;
            } else {
                while (!stack.isEmpty() && nums[i] > stack.peek()) {
                    third = stack.pop();
                }
                stack.push(nums[i]);
            }
        }
        return false;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 456 (132 Pattern)?

This page provides optimized solutions for LeetCode problem 456 (132 Pattern) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 456 (132 Pattern)?

The time complexity for LeetCode 456 (132 Pattern) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 456 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 456 in Java, C++, or Python.

Back to LeetCode Solutions