Coding questions · Meta
Recommend two-hop follows in Python
This question evaluates fluency with graph traversal, set operations, deduplication, and frequency-based ranking in Python, targeting manipulation of directed "follows" relationships represented as dictionaries and is categorized under Data Manipulation (SQL/Python).
Given a directed "follows" graph as a Python dict[str, list[str]], implement recommend_two_hop(graph, user) that returns the set (or a sorted list) of accounts followed by the user’s followees that the user does not already follow, excluding the user themself. Deduplicate recommendations; if you return a list, sort by descending frequency among two-hop neighbors, then lexicographically. Example: graph = {"A": ["B","C"], "B": ["C","D"], "C": ["E"]} ⇒ recommend_two_hop(graph, "A") = {"D","E"}.
Recommend two-hop follows (friend-of-a-friend) in a directed graph
You are given a directed "follows" graph stored in a SQL table.
For a given user (use user_id = 'A' for this question), recommend accounts that are followed by the user's followees (i.e., two-hop neighbors), but that the user does NOT already follow. Also exclude recommending the user themself.
Return one row per recommended account with:
- recommended_user: the recommended account
- frequency: how many of the user's direct followees follow that recommended account
Deduplicate recommendations by recommended_user and compute frequency as the count of distinct direct followees that point to that recommended user.
Sort results by:
- frequency DESC
- recommended_user ASC (lexicographically)
Example intuition: if A follows B and C, and both B and C follow D, then D should appear once with frequency = 2.
Table follows
| column | type | constraints |
|---|---|---|
| follower | VARCHAR(50) | NOT NULL |
| followee | VARCHAR(50) | NOT NULL |
Sample data:
| followee | follower |
|---|---|
| B | A |
| C | A |
| C | B |
| D | B |
| E | B |
| A | B |
| D | C |
| F | C |
| E | C |
Expected output
Two-hop follow recommendations for user 'A' excluding accounts A already follows (B, C) and excluding A themself. Includes frequency counts and is sorted by frequency descending then recommended_user ascending.
| frequency | recommended_user |
|---|---|
| 2 | D |
| 2 | E |
| 1 | F |
Hints
- First get the user's direct followees, then join follows again to reach two hops.
- Exclude recommendations that are already directly followed using an anti-join (LEFT JOIN ... IS NULL) or NOT EXISTS.
- Use COUNT(DISTINCT via_followee) to compute frequency and deduplicate paths.