Problem Link

Description


Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].

Return true if there is a 132 pattern in nums, otherwise, return false.

 

Example 1:

Input: nums = [1,2,3,4]
Output: false
Explanation: There is no 132 pattern in the sequence.

Example 2:

Input: nums = [3,1,4,2]
Output: true
Explanation: There is a 132 pattern in the sequence: [1, 4, 2].

Example 3:

Input: nums = [-1,3,2,0]
Output: true
Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].

 

Constraints:

  • n == nums.length
  • 1 <= n <= 2 * 105
  • -109 <= nums[i] <= 109

Solution


C++

class Solution {
public:
    bool find132pattern(vector<int>& nums) {
        int N = nums.size();
        stack<int> st;
        int midElement = INT_MIN;
 
        for (int i = N - 1; i >= 0; i--) {
            if (nums[i] < midElement) return true;
 
            while (!st.empty() && nums[i] > st.top()) {
                midElement = st.top(); st.pop();
            }
 
            st.push(nums[i]);
        }
 
        return false;
    }
};

Python3

class Solution:
    def find132pattern(self, nums: List[int]) -> bool:
        N = len(nums)
        stack = [] # to maintain a monotonic decreasing stack
        s3 = -inf
 
        for i in range(N - 1, -1, -1):
            if nums[i] < s3: # represents nums[i] < nums[k]
                return True
 
            # when this condition meets, nums[i] here will be nums[j], the third element
            # while the popped element is nums[k], the s3 element
            # s3 will always be the largest possible element, because when a smaller element is encountered, the answer would have already been returned
            # In short, the below function ensures (j, k) -> which nums[j] > nums[k]
            while stack and nums[i] > stack[-1]:
                s3 = stack.pop()
            
            stack.append(nums[i])
 
        return False