Minimum Number of People to Teach Problem
Description
LeetCode Problem 1733.
On a social network consisting of m users and some friendships between users, two users can communicate with each other if they know a common language.
You are given an integer n, an array languages, and an array friendships where:
- There are
nlanguages numbered1throughn, languages[i]is the set of languages thei^thuser knows, andfriendships[i] = [u_i, v_i]denotes a friendship between the usersu_iandv_i.
You can choose one language and teach it to some users so that all friends can communicate with each other. Return the minimum number of users you need to teach.
Note that friendships are not transitive, meaning if x is a friend of y and y is a friend of z, this doesn't guarantee that x is a friend of z.
Example 1:
Input: n = 2, languages = [[1],[2],[1,2]], friendships = [[1,2],[1,3],[2,3]]
Output: 1
Explanation: You can either teach user 1 the second language or user 2 the first language.
Example 2:
Input: n = 3, languages = [[2],[1,3],[1,2],[3]], friendships = [[1,4],[1,2],[3,4],[2,3]]
Output: 2
Explanation: Teach the third language to users 1 and 3, yielding two users to teach.
Constraints:
2 <= n <= 500languages.length == m1 <= m <= 5001 <= languages[i].length <= n1 <= languages[i][j] <= n1 <= u_i < v_i <= languages.length1 <= friendships.length <= 500- All tuples
(u_i,v_i)are unique languages[i]contains only unique values
Solution
Approach: Simulation + Counting
Look at each friendship. If the two people share a language, nothing is needed; otherwise at least one of them must learn something. Put everyone from such friendships into a set s.
We will teach a single language to the people in s who do not know it. For each language, count how many people in s already know it and take the maximum, mx. The best choice is that language, and the answer is |s| - mx.
Complexity: O(k * m) time for checking the friendships (k friendships, m languages per person) plus O(|s| * m) for counting.
from collections import Counter
class Solution:
def minimumTeachings(
self, n: int, languages: List[List[int]], friendships: List[List[int]]
) -> int:
def check(u: int, v: int) -> bool:
for x in languages[u - 1]:
for y in languages[v - 1]:
if x == y:
return True
return False
s = set()
for u, v in friendships:
if not check(u, v):
s.add(u)
s.add(v)
cnt = Counter()
for u in s:
for l in languages[u - 1]:
cnt[l] += 1
return len(s) - max(cnt.values(), default=0)