75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

496. Next Greater Element I

Brute force

Code

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
        vector<int> ans;
        int n = nums1.size();
        int m = nums2.size();
        bool find = false;
        bool found = false;
        for(int i = 0; i< n;i++){
            for(int j = 0; j< m;j++){
                if(find && nums2[j]>nums1[i]){
                    ans.push_back(nums2[j]);
                    found = true;
                    break;
                }
                if(nums1[i]==nums2[j]){
                    find = true;
                }
            }
            if(!found){
                ans.push_back(-1);
            }
            find = false;
            found = false;
        }
        return ans;
    }
};

Monotonic stack + map

Code

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2)
    {
        unordered_map<int, int> mp;
        stack<int> st; // decreasing stack bottom to top
        int n = nums2.size();
        for (int i = 0; i < n; i++) {
            while (!st.empty() && nums2[i] > st.top()) {
                mp[st.top()] = nums2[i];
                st.pop();
            }
            st.push(nums2[i]);
        }
        vector<int> ans;
        for (auto x : nums1) {
            ans.push_back(mp.count(x) ? mp[x] : -1);
        }
        return ans;
    }
};