|
| 1 | +/** |
| 2 | + * 1733. Minimum Number of People to Teach |
| 3 | + * https://leetcode.com/problems/minimum-number-of-people-to-teach/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * On a social network consisting of m users and some friendships between users, two users can |
| 7 | + * communicate with each other if they know a common language. |
| 8 | + * |
| 9 | + * You are given an integer n, an array languages, and an array friendships where: |
| 10 | + * - There are n languages numbered 1 through n, |
| 11 | + * - languages[i] is the set of languages the ith user knows, and |
| 12 | + * - friendships[i] = [ui, vi] denotes a friendship between the users ui and vi. |
| 13 | + * |
| 14 | + * You can choose one language and teach it to some users so that all friends can communicate |
| 15 | + * with each other. Return the minimum number of users you need to teach. |
| 16 | + * |
| 17 | + * Note that friendships are not transitive, meaning if x is a friend of y and y is a friend of |
| 18 | + * z, this doesn't guarantee that x is a friend of z. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {number} n |
| 23 | + * @param {number[][]} languages |
| 24 | + * @param {number[][]} friendships |
| 25 | + * @return {number} |
| 26 | + */ |
| 27 | +var minimumTeachings = function(n, languages, friendships) { |
| 28 | + const languageUsers = Array.from({ length: n + 1 }, () => new Set()); |
| 29 | + const nonCommunicating = new Set(); |
| 30 | + |
| 31 | + for (let i = 0; i < languages.length; i++) { |
| 32 | + for (const lang of languages[i]) { |
| 33 | + languageUsers[lang].add(i + 1); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + for (const [u, v] of friendships) { |
| 38 | + let canCommunicate = false; |
| 39 | + for (const lang of languages[u - 1]) { |
| 40 | + if (languages[v - 1].includes(lang)) { |
| 41 | + canCommunicate = true; |
| 42 | + break; |
| 43 | + } |
| 44 | + } |
| 45 | + if (!canCommunicate) { |
| 46 | + nonCommunicating.add(u); |
| 47 | + nonCommunicating.add(v); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + let result = Infinity; |
| 52 | + for (let lang = 1; lang <= n; lang++) { |
| 53 | + let usersToTeach = 0; |
| 54 | + for (const user of nonCommunicating) { |
| 55 | + if (!languages[user - 1].includes(lang)) { |
| 56 | + usersToTeach++; |
| 57 | + } |
| 58 | + } |
| 59 | + result = Math.min(result, usersToTeach); |
| 60 | + } |
| 61 | + |
| 62 | + return result; |
| 63 | +}; |
0 commit comments