1263D. Secret Passwords - Codeforces Solution C++

  Problem Link : 1263D. Secret Passwords 


✅ C++ Solution :

 
#include<bits/stdc++.h>
using namespace std;

int parent[200001];

int find(int v)
{
	if(parent[v]==v)
		return v;

	return parent[v]=find(parent[v]);
}


int main()
{
	int n,a,b;
	cin>>n;
	for(int i=1;i<=n;i++)
		parent[i]=i;

	string s;
	unordered_set<int> hash[27];
	for(int i=1;i<=n;i++)
	{
		cin>>s;
		for(int j=0;j<s.length();j++)
			hash[s[j]-'a'].insert(i);
	}

	for(int i=0;i<27;i++)
	{
		auto it=hash[i].begin();
		if(it==hash[i].end())
		    continue;
		auto it2=it;
		it2++;
		for(;it2!=hash[i].end();it++,it2++)
		{
			a=find(*it);
			b=find(*it2);
			if(a!=b)
				parent[a]=b;
		}
	}
	int cnt=0;
	for(int i=1;i<=n;i++)
		if(parent[i]==i)
			cnt++;

	cout<<cnt<<"\n";	



}

 

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!!