132 Pattern in C++


Suppose we have a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj. So we have to design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list. So for example, if the input is like [-1, 3, 2, 0], then the output will be true, as there are three patterns [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].

To solve this, we will follow these steps −

  • n := size of nums, if n is 0, then return false

  • define an array called minVals of size n, set minVals[0] := nums[0]

  • for I in range 1 to n – 1

    • minVals[i] := minimum of minVals[i - 1] and nums[i]

  • create stack st

  • for I in range n – 1 down to 1

    • minVal := minVals[i – 1]

    • curr := nums[j]

    • while st is not empty and top of the stack is <= minVal

      • delete from stack st

    • if st is not empty and top of stack < curr, then return true

    • insert nums[i] into s

  • return false

Example (C++)

Let us see the following implementation to get a better understanding −

 Live Demo

-->

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   bool find132pattern(vector<int>& nums) {
      int n = nums.size();
      if(!n) return false;
      vector <int> minVals(n);
      minVals[0] = nums[0];
      for(int i = 1; i < n; i++){
         minVals[i] = min(minVals[i - 1], nums[i]);
      }
      stack <int> s;
      for(int i = n - 1; i > 0; i--){
         int minVal = minVals[i - 1];
         int curr = nums[i];
         while(!s.empty() && s.top() <= minVal) s.pop();
         if(!s.empty() && s.top() < curr) return true;
         s.push(nums[i]);
      }
      return false;
   }
};
main(){
   vector<int> v = {-1,3,2,0};
   Solution ob;
   cout << (ob.find132pattern(v));
}

Input

[-1,3,2,0]

Output

1

Updated on: 29-Apr-2020

268 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements