75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

Help Classmates

Next smaller element

Code

class Solution {
public:
    vector<int> help_classmate(vector<int> arr, int n)
    {
        stack<pair<int, int>> st;
        vector<int> ans(n, -1);
        for (int i = 0; i < n; i++)
        {
            while (!st.empty() && st.top().first > arr[i])
            {
                ans[st.top().second] = arr[i];
                st.pop();
            }
            st.push({arr[i], i});
        }
        return ans;
    }
};