cswork / libraryOpen practice workspace

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:

  1. frequency DESC
  2. 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

columntypeconstraints
followerVARCHAR(50)NOT NULL
followeeVARCHAR(50)NOT NULL

Sample data:

followeefollower
BA
CA
CB
DB
EB
AB
DC
FC
EC

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.

frequencyrecommended_user
2D
2E
1F

Hints

  1. First get the user's direct followees, then join follows again to reach two hops.
  2. Exclude recommendations that are already directly followed using an anti-join (LEFT JOIN ... IS NULL) or NOT EXISTS.
  3. Use COUNT(DISTINCT via_followee) to compute frequency and deduplicate paths.