KatInterview

Mutual Connections: Find Shared Friends from Follow Data

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsgraphsset-intersectionsocial-network

Last 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:

  • x and y are distinct users with x < y (lexicographic order).
  • f is a user who is mutually friends with both x and y.
  • f is neither x nor y.

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] registers A as 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.