Skip to content

Commit f7af630

Browse files
authored
Merge pull request neetcode-gh#3033 from The-SS/main
Create 0456-132-pattern.cpp
2 parents 6de1058 + 3f711df commit f7af630

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

cpp/0456-132-pattern.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
Given nums, return true if there is a 132 pattern where
3+
num[i] < nums[k] < nums[j] for i < j < k
4+
5+
Use a monotonically decreasing stack to store a pair
6+
{candidate nums[j], candidate nums[i]} where
7+
candidate nums[i] is the minimum number in nums before j
8+
9+
Traverse nums.
10+
Pop the stack while n >= candidate nums[j] at the top of the stack (n is a better candidate than those)
11+
Then, if stack not empty, check if 132 patter if found --> return True
12+
Else, add the current num as a candidate nums[j] with the current min as the candidate nums[i] then update current min
13+
*/
14+
class Solution {
15+
public:
16+
bool find132pattern(vector<int>& nums) {
17+
stack<pair<int, int>> s;
18+
int curMin = nums[0];
19+
20+
for(auto & n : nums){
21+
// pop all values in stack that have nums[j] candidate <= n
22+
while(!s.empty() && s.top().first <= n){
23+
s.pop();
24+
}
25+
// if stack not empty, check if we found 132 pattern
26+
if(!s.empty() && s.top().second < n) return true;
27+
else{
28+
// add n to stack and update curMin
29+
s.push({n, curMin});
30+
curMin = min(curMin, n);
31+
}
32+
}
33+
return false;
34+
}
35+
};

0 commit comments

Comments
 (0)