132 Pattern

medium array stack monotonic stack

Problem

Given nums, return true if it contains a 132 pattern: indices i < j < k with nums[i] < nums[k] < nums[j].

Inputnums = [3, 1, 4, 2]
Outputtrue
i=1 (1), j=2 (4), k=3 (2): 1 < 2 < 4. ✓

def find132pattern(nums):
    stack = []
    s2 = float('-inf')   # best candidate for '2'
    for x in reversed(nums):
        if x < s2: return True
        while stack and stack[-1] < x:
            s2 = max(s2, stack.pop())
        stack.append(x)
    return False
function find132pattern(nums) {
  const stack = [];
  let s2 = -Infinity;
  for (let i = nums.length - 1; i >= 0; i--) {
    const x = nums[i];
    if (x < s2) return true;
    while (stack.length && stack[stack.length - 1] < x) {
      s2 = Math.max(s2, stack.pop());
    }
    stack.push(x);
  }
  return false;
}
class Solution {
    public boolean find132pattern(int[] nums) {
        Deque<Integer> stack = new ArrayDeque<>();
        int s2 = Integer.MIN_VALUE;
        for (int i = nums.length - 1; i >= 0; i--) {
            int x = nums[i];
            if (x < s2) return true;
            while (!stack.isEmpty() && stack.peek() < x) {
                s2 = Math.max(s2, stack.pop());
            }
            stack.push(x);
        }
        return false;
    }
}
bool find132pattern(vector<int>& nums) {
    stack<int> st;
    int s2 = INT_MIN;
    for (int i = (int)nums.size() - 1; i >= 0; i--) {
        int x = nums[i];
        if (x < s2) return true;
        while (!st.empty() && st.top() < x) {
            s2 = max(s2, st.top()); st.pop();
        }
        st.push(x);
    }
    return false;
}
Time: O(n) Space: O(n)