➤ Problem Link : 818D. Multicolored Cars
✅ C++ Solution :
#include<bits/stdc++.h> using namespace std; #define ll long long int int main() { int color[1000001]={0}; int n,k; cin>>n>>k; int arr[n]; for(int i=0;i<n;i++) cin>>arr[i]; int i=0; unordered_set<int> st; while(i<n && arr[i]!=k) { color[arr[i]]++; st.insert(arr[i]); i++; } if(i==n) cout<<*(st.begin()); else if(st.size()==0) cout<<"-1"; else{ color[arr[i]]++; while(1) { i++; while(i<n && arr[i]!=k) { color[arr[i]]++; i++; } if(i==n) { cout<<*(st.begin()); exit(0); } color[arr[i]]++; auto it=st.begin(); while(it!=st.end()) { if(color[*it] >= color[k]) it++; else { auto temp=it; it++; st.erase(temp); } } if(st.size()==0) { cout<<"-1"; exit(0); } } } }
Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook.
😇Happy Learning!!