progress

~/problems / Graphs / BFS / multi-source BFS

Friend suggestions by mutual friends

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min Citadel Oracle

A small social app has users 0..n-1 and a list of undirected friendships. Each user gets one "people you may know" suggestion.

Write recommend_friends(n: int, friendships: list[tuple[int, int]]) -> list[int], where rec[u] is:

  1. A candidate is a user v != u, not already a friend, with at least one mutual friend.
  2. Prefer the candidate with the most mutual friends; on a tie, the smallest id.
  3. With no candidates, rec[u] = -1.
n = 6
friendships = [(0, 1), (0, 2), (1, 3), (2, 3), (3, 4), (1, 4)]
recommend_friends(n, friendships)   # [3, 2, 1, 0, 0, -1]
# user 0: friends {1, 2}; 3 is reached through 1 and 2 (2 mutual), 4 through 1 (1 mutual) -> 3
# user 1: friends {0, 3, 4}; 2 shares 0 and 3 (2 mutual) -> 2
# user 4: friends {1, 3}; 0 shares 1, 2 shares 3 (1 mutual each) -> smaller id 0
# user 5: no friends at all -> -1

Up to 5,000 users and 25,000 friendships, each listed once.

⭐ Bonus: a speed test on that size earns a star if the work depends on the friendships, not on n² (don't check every pair of users).

Show hint

Every candidate is a friend of one of u's friends, reached once through each mutual friend.

Topic: BFS / multi-source BFS. Level-by-level search; seed the queue with every source.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc