KatInterview

Suggest Top Social Connection

Trees & GraphsAuto-graded · 22 test cases
MediumAuto-gradedTrees & Graphsgraphsbfshash-table

Last updated

Find the non-adjacent node in an undirected graph with the maximum count of shared neighbors relative to a target node.

You are given a list of bidirectional user connections friendships, where each entry [u, v] represents a friendship between user u and user v.

Given a specific target_id, select a new connection to suggest to this user based on shared connections.

The recommendation must satisfy the following criteria:

  1. The suggested user must not be target_id and must not currently be direct friends with target_id.
  2. The suggested user must share the maximum number of mutual friends with target_id.
  3. If multiple eligible users share the same maximum number of mutual friends, choose the one with the smallest numerical user ID.
  4. If target_id has no direct friends, or if no eligible candidate has at least one mutual friend with target_id, return None.

Constraints

  • $0 \le \text{len}(friendships) \le 10^5$
  • user_id values are non-negative integers.
  • All connections are bidirectional (undirected).

Examples

Example 1

Input: recommend_friend([[1, 2], [1, 3], [2, 4], [3, 4], [3, 5]], 1)

Output: 4

Example 2

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

Output: None

Hints

Hint 1

You only need to inspect users who are exactly 2 steps away (distance 2) from the target_id.

Hint 2

Build an adjacency set for each user to easily check if a candidate is already a direct friend in O(1) time.

Hint 3

Traverse all direct neighbors of target_id, then iterate through each neighbor's friends to count shared connections.