This is my approach where I use map as frequency table.
I checked cases when freq of element >3 and max element occurring twice.
I’ve looked accepted answers in C++ majorly use the same logic but uses frequency array instead of map. Can anyone point to me where my approach is going wrong?
#include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
while(t--)
{
long long n;
cin>>n;
vector<long long> a(n);
for(long long i=0;i<n;i++)
cin>>a[i];
map<long long,long long> h;
bool flag=false;
long long maxx=-INT_MAX;
for(auto i:a)
{
maxx=max(maxx,i);
if(h.find(i)!=h.end())
{
h[i]+=1;
if(h[i]>2)
{
cout<<"NO\n";
flag=true;
break;
}
}
else
h[i]=1;
}
if(flag)
continue;
if(h[maxx]>1)
{
cout<<"NO\n";
continue;
}
for(auto i:h)
{
cout<<i.first<<" ";
h[i.first]--;
}
for(auto i:h)
if(h[i.first]==0)
h.erase(i.first);
if(!h.empty())
{ for(auto itr = h.rbegin(); itr != h.rend(); ++itr)
cout<<itr->first<<" ";
}
cout<<endl;
}
return 0;
}
`