Nearest Smaller Element

Given an array, find the nearest smaller element G[i] for every element A[i] in the array such that the element has an index smaller than i.

More formally,

G[i] for an element A[i] is an element A[j] such that 
    j is maximum possible AND 
    j < i AND
    A[j] < A[i]

Elements for which no smaller element exist, consider the next smaller element as -1.

Example:

Input:  n = 8, a = [39, 27, 11 ,4 ,24, 32 ,32, 1]
Output: -1 -1 -1 -1 4 24 24 -1 

Approach

C++

#include <bits/stdc++.h>
using namespace std;

void nearestSmallestElements(int nint a[])
{
    stack<intst;
    int arr[n];
    for (int i = 0i < ni++)
    {
        while (!st.empty() && st.top() >= a[i])
            st.pop();
        if (st.empty())
            arr[i] = -1;
        else
            arr[i] = st.top();
        st.push(a[i]);
    }
    for (int i = 0i < ni++)
        cout << arr[i<< " ";
}
int main()
{
    int n = 8;
    int a[n] = {39271142432321};

    nearestSmallestElements(na);

    return 0;
}


No comments:

Post a Comment