Mutual Connections: Find Shared Friends from Follow Data
Trees & GraphsAuto-graded · 19 test casesLast updated
Tests graph reciprocity reasoning and set intersection: given directed follow edges, identify all users who are mutual friends with both members of every user pair.
Problem
You are given a list of directed follow relationships between users. Each element is a two-element list [follower, followee].
A mutual friendship between two users exists only when each follows the other: both [A, B] and [B, A] must appear in the input. A one-way follow does not count.
Given the edge list, return every triple [x, y, f] where:
xandyare distinct users withx < y(lexicographic order).fis a user who is mutually friends with bothxandy.fis neitherxnory.
Output format
Return a list of [user1, user2, common_friend] lists. The output must be sorted primarily by user1, then by user2, then by common_friend (all lexicographic).
If a pair (x, y) has no shared mutual friends, it produces no rows in the output.
Rules and edge cases
- An entry whose length is not exactly 2 must be silently ignored.
- A self-loop
[A, A]registersAas a known user but can never form a friendship. - Duplicate edges (the same
[A, B]appearing more than once) must be treated as a single edge; they must not inflate results. - Every user mentioned in any valid edge is part of the universe, even if they end up with no friends at all.
Constraints
0 <= len(edges) <= 10^4- Each valid edge contains exactly 2 non-empty strings.
- User identifiers are non-empty strings containing only uppercase and lowercase ASCII letters and digits.
- The same ordered pair
[A, B]may appear multiple times.
Examples
Example 1
Input: shared_mutual_friends([['A', 'B'], ['B', 'A'], ['A', 'C'], ['C', 'A'], ['A', 'D'], ['D', 'A'], ['B', 'C'], ['C', 'B']])
Output: [['A', 'B', 'C'], ['A', 'C', 'B'], ['B', 'C', 'A'], ['B', 'D', 'A'], ['C', 'D', 'A']]
Hints
Hint 1
Start by collecting all valid directed edges into a set — this automatically deduplicates repeated entries and gives O(1) membership tests.
Hint 2
Two users are mutual friends if and only if both directed edges between them exist in your set. Build a symmetric friend-set for each user by checking both directions.
Hint 3
To find shared friends for every pair (x, y), intersect the friend sets of x and y. Iterate over all pairs with x < y using sorted user order to guarantee the required output ordering.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Step 1 — Build a deduplicated directed edge set
Iterate over the input once. Skip any entry whose length is not 2. Add each valid (a, b) pair to a Python set. Because sets ignore duplicates, repeated edges collapse automatically. Self-loops are excluded at insertion time by checking a != b. All mentioned users are collected into a separate users set.
Step 2 — Derive symmetric mutual-friendship sets
For every directed edge (a, b) in the set, check whether the reverse (b, a) is also present. If so, the pair is mutually connected: add b to friends[a] and a to friends[b]. This is the graph-reciprocity test. Because we iterate over a set and write into sets, there is no risk of double-counting.
Step 3 — Enumerate pairs and intersect friend sets
Sort all users lexicographically. Use a nested loop where the inner index always starts above the outer index; this generates every unordered pair (x, y) with x < y exactly once. Compute friends[x] & friends[y] (set intersection). Sort the resulting shared friends and append [x, y, f] for each. The guard f != x and f != y is satisfied automatically because self-loops were excluded in Step 1 (a user can never be in their own friend set), but the check is retained for clarity.
Why it is correct
- The
directedset mirrors a SQLDISTINCTon raw edges. - The
(b, a) in directedtest is exactly the reciprocity self-join. - Set intersection gives precisely the users who are friends with both members of the pair.
- Enumerating sorted users with
yalways afterxguaranteesuser1 < user2and deterministic ordering without a final sort of the full output.
Complexity
- Time: O(E) to build
directedandfriends, plus O(U² · d̄) for the pair loop, where U is the number of distinct users and d̄ is the average friend-set size. Sorting each intersection adds O(d̄ log d̄) per pair. - Space: O(E + U) for the edge set and friend sets, plus O(R) for the output of R result rows.
Full solution
from typing import List
def shared_mutual_friends(edges: List[List[str]]) -> List[List[str]]:
directed = set()
users = set()
for edge in edges:
if len(edge) != 2:
continue
a, b = edge
users.add(a)
users.add(b)
if a != b:
directed.add((a, b)) # deduplication via set
friends = {user: set() for user in users}
for a, b in directed:
if (b, a) in directed: # both directions exist => mutual
friends[a].add(b)
friends[b].add(a)
result = []
ordered_users = sorted(users)
for i, x in enumerate(ordered_users):
for y in ordered_users[i + 1:]:
for f in sorted(friends[x] & friends[y]):
if f != x and f != y:
result.append([x, y, f])
return result