Rank Suggested Connections by Shared Friends
Trees & GraphsAuto-graded · 18 test casesLast 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]makesuexist, but it adds no friend and does not change anyone's friend count. - A candidate is any existing user who is not
target_userand is not already a friend oftarget_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:
- Mutual count, larger first.
- Degree, larger first, when mutual counts are equal.
- 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_useris 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).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Build the graph. Create a dictionary mapping each user to a set of friends. For each pair
[a, b], add each user to the other's set. Ifa == b, only register the user with an empty set, so they still exist but gain no friend. Sets remove duplicate pairs automatically. - Find the target's friends. Use
graph.get(target_user, set()). This is empty if the target never appears, and the lookup does not insert a new key. - Score every candidate. Loop over all existing users. Skip the target and the target's friends. For each remaining user, the mutual count is
len(target_friends & friends), and the degree islen(friends). - Sort. Sort tuples
(-mutual, -degree, user_id). Python compares tuples element by element, so this applies all three rules in order. IDs are unique, so the order is fully determined.
Why it is correct
- A mutual friend of the target and a candidate is a user in both friend sets, so the set intersection gives the exact count.
- Using sets means repeated or reversed pairs never inflate degrees or mutual counts. Ignoring self-pairs as friendships keeps degrees accurate.
- The loop covers every existing user, so candidates with zero mutual friends are included. When the target is absent, the target's friend set is empty, every mutual count is 0, and the order falls back to degree and then ID.
- Negating the first two keys gives descending order for them while the ID stays ascending.
Complexity
Let E be the number of pairs and V the number of users.
- Building the graph takes O(E) time.
- Each intersection costs at most the size of the smaller set, which is at most the candidate's degree. The sum over all candidates is therefore O(E).
- Sorting takes O(V log V).
- Total: O(E + V log V) time and O(V + E) space.
Reference solution
from typing import List
def suggest_connections(friendships: List[List[int]], target_user: int) -> List[int]:
graph = {}
for a, b in friendships:
if a == b:
graph.setdefault(a, set())
continue
graph.setdefault(a, set()).add(b)
graph.setdefault(b, set()).add(a)
target_friends = graph.get(target_user, set())
ranked = []
for user, friends in graph.items():
if user == target_user or user in target_friends:
continue
mutual = len(target_friends & friends)
ranked.append((-mutual, -len(friends), user))
ranked.sort()
return [user for _, _, user in ranked]