Suggest Top Social Connection
Trees & GraphsAuto-graded · 22 test casesLast 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:
- The suggested user must not be
target_idand must not currently be direct friends withtarget_id. - The suggested user must share the maximum number of mutual friends with
target_id. - If multiple eligible users share the same maximum number of mutual friends, choose the one with the smallest numerical user ID.
- If
target_idhas no direct friends, or if no eligible candidate has at least one mutual friend withtarget_id, returnNone.
Constraints
- $0 \le \text{len}(friendships) \le 10^5$
user_idvalues 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To identify the best recommendation, we only need to consider candidates who share at least one mutual friend with target_id. These candidates are precisely the nodes at distance 2 from target_id in the network graph.
- Adjacency Representation: We represent the graph using an adjacency dictionary mapping each user ID to a
setof their direct friends. Using sets ensures fast $O(1)$ membership checking and eliminates duplicate edge issues. - 2-Hop Traversal: Retrieve the set of direct friends of
target_id. For each direct friend $f$, iterate over all neighbors $c$ of $f$. - Filtering:
- $c$ cannot be
target_id. - $c$ cannot be in the direct friends set of
target_id.
- $c$ cannot be
- Frequency Counting: Increment a counter for each valid candidate $c$. The final count for $c$ represents the total number of mutual friends shared between $c$ and
target_id. - Selection: If the candidate count map is empty, return
None. Otherwise, select the candidate that maximizescounts[c], breaking ties by picking the smallest candidate ID. In Python, this can be succinctly expressed withmin(counts, key=lambda candidate: (-counts[candidate], candidate)).
Complexity Analysis
Let $E$ be the total number of friendships (edges) in the input graph.
- Time Complexity: $O(E)$. Building the graph takes $O(E)$ time. Traversing the 2-hop neighborhood of
target_idtakes $O(\sum_{f \in N(\text{target})} \text{degree}(f))$ time, which is bounded by $O(E)$. Finding the optimal candidate from the aggregated counts takes $O(K)$ time, where $K$ is the number of 2-hop candidates ($K \le E$). Thus, overall time complexity is $O(E)$. - Space Complexity: $O(E)$ to store the adjacency list representation of the network.
Python Reference Solution
from typing import List, Optional
from collections import defaultdict
def recommend_friend(friendships: List[List[int]], target_id: int) -> Optional[int]:
# Construct an undirected graph with sets for O(1) membership checks
graph = defaultdict(set)
for u, v in friendships:
graph[u].add(v)
graph[v].add(u)
direct_friends = graph.get(target_id, set())
if not direct_friends:
return None
# Count mutual friends for each potential candidate (distance-2 nodes)
counts = defaultdict(int)
for friend in direct_friends:
for candidate in graph[friend]:
if candidate != target_id and candidate not in direct_friends:
counts[candidate] += 1
if not counts:
return None
# Select candidate with highest count; tie-break by smallest candidate ID
return min(counts, key=lambda candidate: (-counts[candidate], candidate))