#456

132 Pattern

Medium
ArrayBinary SearchStackMonotonic StackOrdered SetHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a stack to keep track of potential candidates for the 132 pattern. This reduces the time complexity significantly by only needing to traverse the array once.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an empty stack and a variable 'second' to negative infinity.
  2. 2Step 2: Traverse the array from right to left. For each number, check if it is less than 'second'. If yes, return true (found a 132 pattern).
  3. 3Step 3: If not, while the stack is not empty and the current number is greater than the top of the stack, pop the stack and update 'second' to the popped value.
  4. 4Step 4: Push the current number onto the stack and continue until the end of the array.
solution.py10 lines
1# Full working Python code
2stack = []
3second = float('-inf')
4for num in reversed(nums):
5    if num < second:
6        return True
7    while stack and num > stack[-1]:
8        second = stack.pop()
9    stack.append(num)
10return False

Complexity note: The time complexity is O(n) because we traverse the array once. The space complexity is O(n) due to the stack used to store elements.

  • 1The 132 pattern requires careful tracking of potential candidates.
  • 2Using a stack can help efficiently manage the conditions for the pattern.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.