
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 −
-->
#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
- Related Articles
- Adapter Pattern in C++?
- Word Pattern in C++
- Printing Heart Pattern in C
- Composite Design Pattern in C++
- Repeated Substring Pattern in C++
- Printing Interesting pattern in C++
- Word Pattern II in C++
- Different Star Pattern Programs in C#
- Pattern matching in C# with Regex
- Printing Different pattern Bash in C++
- Program to print number pattern in C
- Program to print Diamond Pattern in C
- Program to print numeric pattern in C
- Program to print pyramid pattern in C
- Program to print Interesting pattern in C++
