Suppose we have a list of numbers called nums, we have to check whether there are triplets (i, j, k) such that i < j < k and nums[i] < nums[k] < nums[j].
So, if the input is like nums = [2, 12, 1, 4, 4], then the output will be True, as [2, 12, 4] matches the criteria because 2 < 4 < 12.
To solve this, we will follow these steps −
n := size of nums
Define an array left of size n
left[0] := nums[0]
for initialize i := 1, when i < n, update (increase i by 1), do −
left[i] := minimum of nums[i] and left[i - 1]
Define one stack st
for initialize i := n - 1, when i >= 1, update (decrease i by 1), do −
x := left[i - 1]
while st is not empty and top of st <= x, do −
pop from st
if st is not empty and x < nums[i] and nums[i] > top of st, then −
return true
push nums[i] into st
return false
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool solve(vector<int>& nums) {
int n = nums.size();
vector<int> left(n);
left[0] = nums[0];
for (int i = 1; i < n; i++) {
left[i] = min(nums[i], left[i - 1]);
}
stack<int> st;
for (int i = n - 1; i >= 1; i--) {
int x = left[i - 1];
while (!st.empty() && st.top() <= x)
st.pop();
if (!st.empty() && x < nums[i] && nums[i] > st.top())
return true;
st.push(nums[i]);
}
return false;
}
};
bool solve(vector<int>& nums) {
return (new Solution())->solve(nums);
}
int main(){
vector<int> v = {2, 12, 1, 4, 4};
cout << solve(v);
}Input
{2, 12, 1, 4, 4}Output
1