1733. Minimum Number of People to Teach
Description
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 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 minimumnumber 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 3, yielding two users to teach.
Constraints:
2 <= n <= 500languages.length == m1 <= m <= 5001 <= languages[i].length <= n1 <= languages[i][j] <= n1 <= ui < vi <= languages.length1 <= friendships.length <= 500- All tuples
(ui, vi)are unique languages[i]contains only unique values
Solutions
Solution: Greedy
- Time complexity: O(mn)
- Space complexity: O(mn)
JavaScript
js
/**
* @param {number} n
* @param {number[][]} languages
* @param {number[][]} friendships
* @return {number}
*/
const minimumTeachings = function (n, languages, friendships) {
const m = languages.length;
const languageKnows = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(false));
const users = new Set();
let result = m;
for (let index = 0; index < m; index++) {
const user = index + 1;
for (const language of languages[index]) {
languageKnows[user][language] = true;
}
}
for (const [u, v] of friendships) {
const isCommunicable = languageKnows[u].some((isKnow, language) => {
return isKnow && languageKnows[v][language];
});
if (isCommunicable) continue;
users.add(u);
users.add(v);
}
for (let language = 1; language <= n; language++) {
let teach = 0;
for (const user of users) {
if (!languageKnows[user][language]) {
teach += 1;
}
}
result = Math.min(teach, result);
}
return result;
};