Ctrl K

Lessons in One Shared Language

Medium
A club has len(speaks) members, numbered from 1. There are language_count languages, also numbered from 1. The list speaks[i] holds the languages that member i + 1 knows. Each pair [u, v] in pairs means members u and v are friends. Two friends can talk if they share at least one language. You pick **one** language and teach it to some members so that afterwards every pair of friends can talk. Return the fewest members you have to teach. Friendship is not transitive: if u is friends with v and v with w, that does not make u and w friends.
Example 1
language_count=3, speaks=[[1], [2, 3], [3]], pairs=[[1, 2], [2, 3], [1, 3]] → 1

Pairs 1–2 and 1–3 cannot talk. Teaching person 1 language 3 is enough, since persons 2 and 3 both know it.

Example 2
language_count=2, speaks=[[1], [1, 2], [2]], pairs=[[1, 2], [2, 3]] → 0

Every pair already shares a language, so nobody needs lessons.

Constraints
  • 2 ≤ language_count ≤ 500
  • 1 ≤ len(speaks) ≤ 500
  • 1 ≤ len(speaks[i]) ≤ language_count; the languages in speaks[i] are distinct and between 1 and language_count
  • 1 ≤ len(pairs) ≤ 500
  • For each pair 1 ≤ u, v ≤ len(speaks) and u ≠ v; no two friends are listed as a pair twice
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsJobs With a Cooldown MediumSorted Into Runs of Three MediumFewest Guests by Lanyard Color MediumDeal Into Consecutive Sets MediumPair Each Number With Its Double Medium
loading Python…
Input
language_count=3, speaks=[[1], [2, 3], [3]], pairs=[[1, 2], [2, 3], [1, 3]]
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 70 tests on the server, hidden ones included.