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
n
languages numbered1
throughn
, languages[i]
is the set of languages theith
user knows, andfriendships[i] = [ui, vi]
denotes a friendship between the usersui
andvi
.
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 ifx
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 2, yielding two users to teach.
Constraints:
2 <= n <= 500
languages.length == m
1 <= m <= 500
1 <= languages[i].length <= n
1 <= languages[i][j] <= n
1 <= ui < vi <= languages.length
1 <= friendships.length <= 500
- All tuples
(ui, vi)
are unique languages[i]
contains only unique values
Generating G
takes O(LN)
time and O(LN)
space.
Generating s
takes O(FN)
time and O(L)
space.
Iterating all the languages and count the number of people to teach takes O(NL)
time.
So overall it takes O((L + F) * N)
time, and O(LN)
space.
// OJ: https://leetcode.com/problems/minimum-number-of-people-to-teach/
// Author: github.com/lzl124631x
// Time: O((L + F) * N)
// Space: O(LN)
class Solution {
public:
int minimumTeachings(int n, vector<vector<int>>& L, vector<vector<int>>& F) {
int M = L.size();
vector<unordered_set<int>> G(M); // people to language
for (int i = 0; i < M; ++i) {
for (int n : L[i]) G[i].insert(n - 1);
}
unordered_set<int> s;
for (auto &f : F) {
int a = f[0] - 1, b = f[1] - 1, i;
for (i = 0; i < n; ++i) {
if (G[a].count(i) && G[b].count(i)) break;
}
if (i == n) s.insert(a), s.insert(b);
}
int ans = INT_MAX;
for (int i = 0; i < n; ++i) { // try each language
int cnt = 0;
for (int p : s) {
cnt += G[p].count(i) == 0;
}
ans = min(ans, cnt);
}
return ans;
}
};