Message on Whatsapp 8879355057 for DSA(OA + Interview) + Fullstack Dev Training + 1-1 Personalized Mentoring to get 10+LPA Job
0 like 0 dislike
921 views
in Online Assessments by Expert (46,090 points) | 921 views

2 Answers

1 like 0 dislike
#include<iostream>

#include<bits/stdc++.h>

using namespace std;

int main()

{
    vector<int>arr{1,3,7,2,5,1,4,2,1,5};
  //we have to find element to the right which have highest frequecny
    //if no then put -1
     unordered_map<int,int>count;
    for(auto i:arr)
    {
        count[i]++;
    }
    //next greater element approach
    //for O(n) soln use stack and compare count of each element
    stack<int>s;
    vector<int>res;
   // res.push_back(-1);//for last element
   int n=arr.size();
    for(int i=n-1;i>=0;i--)
    {
        while(s.empty()==false and count[s.top()]<=count[arr[i]] )
        {
            s.pop();
        }
        if(s.empty())
        {
            res.push_back(-1);
        }
        else{
        res.push_back(s.top());
        }
        s.push(arr[i]);
    }
    reverse(res.begin(),res.end());
    for(auto i:res)
    {
        cout<<i<<" ";
    }
}
by Expert (660 points)
0 like 0 dislike

Images of ques

imageimage

 

by Expert (46,090 points)