KatInterview

Rank Suggested Connections by Shared Friends

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsgraphadjacency-listsorting

Last updated

Build an undirected graph from friendship pairs, then rank every non-friend of a target user by mutual friends, degree and ID using a composite sort key.

Rank Suggested Connections

A social network is described by a list of friendship pairs. Each pair [a, b] means users a and b are friends. Friendship is mutual (the graph is undirected). Given a target_user, return every user who could be suggested to them, in ranked order.

Definitions

  • A user exists if their ID appears in at least one pair, including a pair that links a user to themselves.
  • The friends of a user are the distinct other users they are paired with. Repeated pairs, and the same pair written in either order, count once.
  • A pair [u, u] makes u exist, but it adds no friend and does not change anyone's friend count.
  • A candidate is any existing user who is not target_user and is not already a friend of target_user. Candidates with no friends in common with the target are still candidates.
  • The mutual count of a candidate is the number of users who are friends with both the candidate and the target.
  • The degree of a candidate is their total number of distinct friends.

Ranking

Order the candidates by:

  1. Mutual count, larger first.
  2. Degree, larger first, when mutual counts are equal.
  3. User ID, smaller first, when both of the above are equal.

Return the ordered list of candidate IDs.

If target_user does not appear in any pair, they have no friends, so every existing user is a candidate with mutual count 0. The ranking rules above still apply. If there are no candidates, return an empty list.

Constraints

  • 0 <= len(friendships) <= 10,000
  • Each pair contains two non-negative integer user IDs.
  • IDs may be large and sparse.
  • The same friendship may appear more than once, in either order.
  • target_user is a non-negative integer and may not appear in the input.

Examples

Example 1

Input: suggest_connections([[0, 1], [0, 2], [1, 2], [1, 3], [2, 4], [3, 4]], 0)

Output: [3, 4]

Example 2

Input: suggest_connections([[1, 2], [2, 3]], 1)

Output: [3]

Hints

Hint 1

Build a dictionary from user ID to a set of friends. Insert each pair in both directions, and make sure a self-pair still registers the user without adding a friend.

Hint 2

For each existing user other than the target and the target's friends, the mutual count is the size of the intersection of their friend set with the target's friend set.

Hint 3

Encode all three ranking rules in one sort key: (-mutual, -degree, user_id).