1
# Runtime: 2444 ms (Top 20.45%) | Memory: 28.6 MB (Top 5.68%)4
self, n: int, languages: List[List[int]], friendships: List[List[int]]7
1. Find out users who need to be taught8
2. If no user needs to be taught, return 09
3. For all users who need to be taught a language, find the most popular language among them10
4. Teach that language to rest of the users who need to be taught.12
need_to_be_taught = set()13
languages = [set(language) for language in languages]15
# 1. Find out users who needs to be taught16
for user1, user2 in friendships:17
# Adjust the 1 based indexing to 0 based indexing20
if not (languages[user1] & languages[user2]):21
need_to_be_taught.update([user1, user2])23
# 2. If no user needs to be taught, return 024
if not need_to_be_taught:27
# 3. For all users who needs to be taught a language, find the most popular language among them28
language_spoken_by = collections.defaultdict(int)29
for user in need_to_be_taught:30
# for each user increment the count of languages he can speak31
for language in languages[user]:32
language_spoken_by[language] += 134
# find occurrence of language spoken by maximum users who can't communicate with each other35
popular_language_count = max(language_spoken_by.values())37
# 4. Teach that language to rest of the users who need to be taught.38
return len(need_to_be_taught) - popular_language_count