previous smaller element hackerrank code example

Example: previous smaller element hackerrank

//nearest smaller to left or nearest smaller element
//stack implementation
#include 
#include 
#include 
using namespace std;

vector  left_nearestSmaller(int arr[], int n){
    vector  v;
    stack  s;
    for(int i = 0; i0 && s.top() < arr[i])
            v.push_back(s.top());
        else if(s.size()> 0 && s.top() > arr[i]){
            while(s.size()>0 && s.top() >= arr[i]){
                s.pop();
            }
            if(s.size() == 0)
                v.push_back(-1);
            else
                v.push_back(s.top());
        }
        s.push(arr[i]);
    }
    return v;
}

int main(){
    int n;  cin >> n;
    int arr[n];
    for(int i = 0; i> arr[i];
    }
    vector  vec = left_nearestSmaller(arr, n);
    for(int i = 0; i

Tags:

Misc Example