SDE & MLE Prep

456. 132 Pattern

Problem

Decide whether nums contains a "132 pattern": indices i < j < k with nums[i] < nums[k] < nums[j].

Example: [3,1,4,2] → true (1, 4, 2); [1,2,3,4] → false

Constraints: n ≤ 2·10⁵.

Scan from the right keeping a decreasing stack of candidates for "3" and two = the best "2" (largest value popped, i.e. smaller than some later-left "3"). If the current number is less than two, it's a valid "1".

Complexity: O(n).

class Solution:
    def find132pattern(self, nums: List[int]) -> bool:
        st, two = [], float("-inf")
        for x in reversed(nums):
            if x < two:
                return True
            while st and st[-1] < x:
                two = st.pop()          # x acts as "3", popped value as "2"
            st.append(x)
        return False