Challenge: Friend Groups
Completed
There are n people (0 … n − 1). Process q commands with union-find: friend a b makes a and b friends (their groups merge); ask a b prints yes if they're in the same group, otherwise no. At the end print Groups: <count>.
Input
Line 1: n q. Then q commands.
Output
One line per ask, then the number of groups.
Example
Input
5 5 friend 0 1 friend 2 3 ask 0 3 friend 1 3 ask 0 2
Output
no yes Groups: 2
Editor
Python
Hints
find() follows parents up to the leader.
friend: if the two leaders differ, point one at the other and reduce the group count.
Solution explanation
Counting a merge only when the leaders differ keeps the group count right even for repeated friendships.
Show solution
n, q = map(int, input().split())
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
groups = n
for _ in range(q):
cmd, a, b = input().split()
ra, rb = find(int(a)), find(int(b))
if cmd == "friend":
if ra != rb:
parent[rb] = ra
groups -= 1
else:
print("yes" if ra == rb else "no")
print("Groups:", groups) Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module