Minimum Number of People to Teach — LeetCode 1733 Python Solution
- Problem
- #1733
- Pattern
- Greedy
- Reading time
- 4 min
- Source
- leetcode.com
The 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 n languages numbered 1 through n, languages[i] is the set of languages the ith user knows, and friendships[i] = [ui, vi] denotes a friendship between the users ui and vi.
Example
- 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.
Python solution
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)Complexity
| Measure | Complexity |
|---|---|
| Time | O(m^2 \times k) |
| Space | O(n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 1733. Minimum Number of People to Teach is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1733. Minimum Number of People to Teach?
- LeetCode 1733. Minimum Number of People to Teach is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1733. Minimum Number of People to Teach?
- The Python solution on this page runs in O(m^2 \times k).
- What is the space complexity of LeetCode 1733. Minimum Number of People to Teach?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1733. Minimum Number of People to Teach cover?
- LeetCode 1733. Minimum Number of People to Teach is tagged Greedy, Array and Hash Table on LeetCode.