Minimum Number of People to Teach - Problem
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 numbered 1 through n languages[i]is the set of languages the i-th user knowsfriendships[i] = [u_i, v_i]denotes a friendship between 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.
Input & Output
Example 1 — Basic Communication Problem
$
Input:
n = 2, languages = [[1],[2],[1,2]], friendships = [[1,2],[1,3],[2,3]]
›
Output:
1
💡 Note:
User 1 speaks [1], User 2 speaks [2] - they cannot communicate. User 3 speaks [1,2] and can talk to both. Teaching language 1 to User 2 or language 2 to User 1 solves all problems with 1 person taught.
Example 2 — No Teaching Needed
$
Input:
n = 3, languages = [[2],[1,3],[1,2]], friendships = [[1,2],[1,3],[2,3]]
›
Output:
0
💡 Note:
User 1:[2] and User 2:[1,3] have no common language, but User 1:[2] and User 3:[1,2] share language 2, and User 2:[1,3] and User 3:[1,2] share language 1. All friendships can communicate, so 0 users need teaching.
Example 3 — Multiple Isolated Groups
$
Input:
n = 3, languages = [[1],[2],[3]], friendships = [[1,2],[2,3]]
›
Output:
1
💡 Note:
User 1:[1] and User 2:[2] cannot communicate, User 2:[2] and User 3:[3] cannot communicate. Teaching any language to User 2 allows all three to communicate through User 2 as intermediary.
Constraints
- 2 ≤ n ≤ 500
- languages.length == m
- 1 ≤ m ≤ 500
- 1 ≤ languages[i].length ≤ n
- 1 ≤ languages[i][j] ≤ n
- 1 ≤ friendships.length ≤ 500
- friendships[i].length == 2
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code