Answers for "next greater queries hacker rank"

1

previous smaller element hackerrank

//nearest smaller to left or nearest smaller element
//stack implementation
#include <iostream>
#include <stack>
#include <vector>
using namespace std;

vector <int> left_nearestSmaller(int arr[], int n){
    vector <int> v;
    stack <int> s;
    for(int i = 0; i<n; i++){
        if(s.size() == 0)
            v.push_back(-1);
        else if(s.size()>0 && 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<n; i++){
        cin >> arr[i];
    }
    vector <int> vec = left_nearestSmaller(arr, n);
    for(int i = 0; i<n ; i++){
        cout << vec[i] << " ";
    }
}
Posted by: Guest on July-31-2020

Browse Popular Code Answers by Language