Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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:
n languages numbered 1 through n,languages[i] is the set of languages the ith user knows, andfriendships[i] = [ui, vi] denotes a friendship between the users ui and vi.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 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(ui, vi) are uniquelanguages[i] contains only unique valuesProblem summary: 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. 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Greedy
2 [[1],[2],[1,2]] [[1,2],[1,3],[2,3]]
3 [[2],[1,3],[1,2],[3]] [[1,4],[1,2],[3,4],[2,3]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1733: Minimum Number of People to Teach
class Solution {
public int minimumTeachings(int n, int[][] languages, int[][] friendships) {
Set<Integer> s = new HashSet<>();
for (var e : friendships) {
int u = e[0], v = e[1];
if (!check(u, v, languages)) {
s.add(u);
s.add(v);
}
}
if (s.isEmpty()) {
return 0;
}
int[] cnt = new int[n + 1];
for (int u : s) {
for (int l : languages[u - 1]) {
++cnt[l];
}
}
int mx = 0;
for (int v : cnt) {
mx = Math.max(mx, v);
}
return s.size() - mx;
}
private boolean check(int u, int v, int[][] languages) {
for (int x : languages[u - 1]) {
for (int y : languages[v - 1]) {
if (x == y) {
return true;
}
}
}
return false;
}
}
// Accepted solution for LeetCode #1733: Minimum Number of People to Teach
func minimumTeachings(n int, languages [][]int, friendships [][]int) int {
check := func(u, v int) bool {
for _, x := range languages[u-1] {
for _, y := range languages[v-1] {
if x == y {
return true
}
}
}
return false
}
s := map[int]bool{}
for _, e := range friendships {
u, v := e[0], e[1]
if !check(u, v) {
s[u], s[v] = true, true
}
}
if len(s) == 0 {
return 0
}
cnt := make([]int, n+1)
for u := range s {
for _, l := range languages[u-1] {
cnt[l]++
}
}
return len(s) - slices.Max(cnt)
}
# Accepted solution for LeetCode #1733: Minimum Number of People to Teach
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)
// Accepted solution for LeetCode #1733: Minimum Number of People to Teach
use std::collections::{HashMap, HashSet};
impl Solution {
pub fn minimum_teachings(n: i32, languages: Vec<Vec<i32>>, friendships: Vec<Vec<i32>>) -> i32 {
fn check(u: usize, v: usize, languages: &Vec<Vec<i32>>) -> bool {
for &x in &languages[u - 1] {
for &y in &languages[v - 1] {
if x == y {
return true;
}
}
}
false
}
let mut s: HashSet<usize> = HashSet::new();
for edge in friendships.iter() {
let u = edge[0] as usize;
let v = edge[1] as usize;
if !check(u, v, &languages) {
s.insert(u);
s.insert(v);
}
}
let mut cnt: HashMap<i32, i32> = HashMap::new();
for &u in s.iter() {
for &l in &languages[u - 1] {
*cnt.entry(l).or_insert(0) += 1;
}
}
let mx = cnt.values().cloned().max().unwrap_or(0);
(s.len() as i32) - mx
}
}
// Accepted solution for LeetCode #1733: Minimum Number of People to Teach
function minimumTeachings(n: number, languages: number[][], friendships: number[][]): number {
function check(u: number, v: number): boolean {
for (const x of languages[u - 1]) {
for (const y of languages[v - 1]) {
if (x === y) {
return true;
}
}
}
return false;
}
const s = new Set<number>();
for (const [u, v] of friendships) {
if (!check(u, v)) {
s.add(u);
s.add(v);
}
}
const cnt = new Map<number, number>();
for (const u of s) {
for (const l of languages[u - 1]) {
cnt.set(l, (cnt.get(l) || 0) + 1);
}
}
return s.size - Math.max(0, ...cnt.values());
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.