diff --git a/2.stacks/NearestGreaterElementFromRight.cpp b/2.stacks/NearestGreaterElementFromRight.cpp new file mode 100644 index 000000000..76369da63 --- /dev/null +++ b/2.stacks/NearestGreaterElementFromRight.cpp @@ -0,0 +1,53 @@ +#include +using namespace std; + +// Next Greater Right Element +vector solve(vector a) +{ + // output vector + vector ans; + + stack s; + int n = a.size(); + // from back side + for(int i=n-1;i>=0;i--){ + // base case + if(s.size()==0){ + ans.push_back(-1); + } + else if(s.size()>0 && a[i]0 && a[i]>=s.top()){ + while(s.size()>0 && a[i]>=s.top()){ + s.pop(); + } + if(s.size()==0){ + ans.push_back(-1); + } + else{ + ans.push_back(s.top()); + } + } + s.push(a[i]); + } + // reverse the array bcz element store from back side + reverse(ans.begin(),ans.end()); + + return ans; +} + +int main(){ + int n; + cin>>n; + vector v(n); + for(int i=0;i>v[i]; + } + // print the output + vector ans = solve(v); + for(int i=0;i