Skip to content

Commit

Permalink
Update 37.Next Smaller Element.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
mridul8920 authored Nov 27, 2021
1 parent b91fe59 commit 85bbf26
Showing 1 changed file with 24 additions and 56 deletions.
80 changes: 24 additions & 56 deletions STACK/37.Next Smaller Element.cpp
Original file line number Diff line number Diff line change
@@ -1,61 +1,29 @@
// A Stack based C++ program to find next
// smaller element for all array elements
#include <bits/stdc++.h>
#include<bits/stdc++.h>
using namespace std;

// prints NSE for elements of array arr[] of size n

void printNSE(int arr[], int n)
{
stack<pair<int, int> > s;
vector<int> ans(n);

// iterate for rest of the elements
for (int i = 0; i < n; i++) {
int next = arr[i];

// if stack is empty then this element can't be NSE
// for any other element, so just push it to stack
// so that we can find NSE for it, and continue
if (s.empty()) {
s.push({ next, i });
continue;
}

// while stack is not empty and the top element is
// greater than next
// a) NSE for top is next, use top's index to
// maintain original order
// b) pop the top element from stack

while (!s.empty() && s.top().first > next) {
ans[s.top().second] = next;
s.pop();
}

// push next to stack so that we can find NSE for it

s.push({ next, i });
}

// After iterating over the loop, the remaining elements
// in stack do not have any NSE, so set -1 for them

while (!s.empty()) {
ans[s.top().second] = -1;
s.pop();
}

for (int i = 0; i < n; i++) {
cout << arr[i] << " ---> " << ans[i] << endl;
}
vector<int> smallestGreaterEle(int arr[],int n){
vector<int>v;
stack<int>s;
s.push(arr[n-1]);
v.push_back(-1);
for(int i=n-2;i>=0;i--){
while(!s.empty() and s.top()>=arr[i])
s.pop();
int ns=s.empty()?-1:s.top();
v.push_back(ns);
s.push(arr[i]);
}
reverse(v.begin(),v.end());
return v;
}

// Driver program to test above functions
int main()
{
int arr[] = { 11, 13, 21, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
printNSE(arr, n);
return 0;
int main(){
int arr[]= {11, 13, 21, 3};
int n=4;
// arr[n];
vector<int>v=smallestGreaterEle(arr,n);
for(auto i: v)
cout<<i<<" ";

return 0;
}

0 comments on commit 85bbf26

Please sign in to comment.