Versioned Social Graph: Follow, Snapshot, and Recommend
Data Structure DesignAuto-graded · 20 test casesLast updated
Tests data-structure design for a directed follow graph with copy-on-snapshot history and friend-of-friend recommendations ranked by mutual count.
Versioned Social Graph
You are building an in-memory social network engine that processes a sequence of operations on a directed follow graph.
Implement a function that accepts a list of operation names and their corresponding arguments, executes each operation in order, and returns a parallel list of results — one entry per operation.
Operations
| Operation | Arguments | Returns |
|---|---|---|
"follow" | [follower, followee] | None |
"unfollow" | [follower, followee] | None |
"snapshot" | [] | int — the new snapshot id |
"is_following" | [follower, followee, snapshot_id] | bool |
"following" | [follower, snapshot_id] | List[int] |
"recommend" | [user, k] | List[int] |
Behaviour Rules
follow / unfollow
- Relationships are one-directional:
follow(A, B)means A follows B; B does not automatically follow A. - A user may not follow themselves. Any
followcall wherefollower == followeeis silently ignored and still producesNone. - Calling
followon a pair that is already connected is a no-op (idempotent). - Calling
unfollowon a pair that is not connected is a no-op; it does not raise an error.
snapshot
- Freezes the entire follow graph exactly as it stands at the moment of the call.
- Snapshot ids are integers assigned in order, starting from
0. The firstsnapshotcall returns0, the second returns1, and so on. - Any
followorunfollowoperations executed after a snapshot has been taken do not alter that snapshot in any way.
is_following
- Returns
Trueiffollowerwas followingfolloweein the graph at the timesnapshot_idwas taken;Falseotherwise.
following
- Returns a list of all user ids that
followerwas following at the timesnapshot_idwas taken. - The list must be sorted in strictly ascending order.
- If
followerhad no outgoing follows at that snapshot, return an empty list.
recommend
- Operates on the current live graph, not on any snapshot.
- The recommendation pool consists solely of users that
userdoes not already follow and that can be reached via at least one friend-of-friend path fromuser. Concretely: a candidateCis eligible if and only if there exists at least one userVsuch thatuserfollowsVandVfollowsC, whereC ≠ useranduserdoes not already followC. Users that appear nowhere in the graph, or that have no such mutual connection, are never included in the output. - Score each eligible candidate by counting the number of distinct users
Vsatisfying the condition above (i.e., the number ofuser's followees who also followC). This is the candidate's mutual-connection count. - Sort the eligible candidates: highest mutual-connection count first. Break ties by ascending user id.
- Return the first
kcandidates from this sorted list. If fewer thankeligible candidates exist, return all of them.
Constraints
- All user ids are positive integers.
1 <= k <= 100- Snapshot ids passed to
"is_following"and"following"are always valid (i.e., a"snapshot"call with that id has already been executed). - The total number of operations in one call will not exceed 500.
- User ids will not exceed 1000.
Examples
Example 1
Input: run_graph_operations(['follow', 'follow', 'snapshot', 'unfollow', 'follow', 'follow', 'snapshot', 'is_following', 'is_following', 'is_following', 'following', 'following'], [[1, 2], [1, 3], [], [1, 2], [2, 4], [3, 4], [], [1, 2, 0], [1, 2, 1], [2, 4, 0], [1, 0], [1, 1]])
Output: [None, None, 0, None, None, None, 1, True, False, False, [2, 3], [3]]
Example 2
Input: run_graph_operations(['follow', 'follow', 'follow', 'follow', 'snapshot', 'recommend'], [[1, 2], [1, 3], [2, 4], [3, 4], [], [1, 5]])
Output: [None, None, None, None, 0, [4]]
Hints
Hint 1
For snapshot, take a full deep copy of the adjacency map at that instant. Under the given constraints this is cheap, and it guarantees that later mutations never bleed into frozen history.
Hint 2
For is_following and following, only consult the frozen snapshot dict — never the live graph. The snapshot already holds the correct state for that point in time.
Hint 3
For recommend, iterate over every account that user follows, then over every account each of those followees follows; accumulate scores in a dict. After the loop, exclude user and anyone user already follows, then sort by (-score, id). Users that never appear in the scores dict are not candidates at all.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core data structures
Two objects carry all state:
current: adict[int, set[int]]mapping each user to the set of users they currently follow. This is the live, mutable graph.snapshots: a plain list where indexiholds a frozen deep copy ofcurrenttaken at the moment of thei-thsnapshot()call.
follow / unfollow
Both are O(1) average.
follow calls set.add; adding a duplicate is harmless. Self-follows are dropped with a single equality check before touching the dict.
unfollow calls set.discard, which is a no-op when the edge is absent, so no guard is needed.
snapshot
snapshots.append({u: set(fs) for u, fs in current.items()})
This copies every live set into a brand-new dict. Because each snapshot owns independent set objects, no subsequent mutation of current can reach any frozen snapshot. The copy costs O(E) where E is the number of live edges, which is acceptable under the stated constraints.
The return value is len(snapshots) - 1, giving ids 0, 1, 2, … in order.
is_following / following
Both index directly into snapshots[snapshot_id] — the frozen map — and never touch current.
is_followingis O(1) average (set membership test).followingis O(d log d) where d is the out-degree of the queried user (for the sort).
recommend
The algorithm is a two-level traversal of the live graph:
- For each user
Vthatuserfollows, iterate over every userCthatVfollows. - If
C ≠ useranduserdoes not already followC, incrementscores[C]. - After the loop,
scorescontains exactly the eligible candidates with their mutual-connection counts. Any user not inscoreshas zero mutual connections and is therefore not a candidate — they are never included in the output, even if fewer thankcandidates exist. - Sort by
(-score, id)to get descending score with ascending id as the tiebreak. - Return the first
kentries.
Time: O(F × D + C log C) where F = out-degree of user, D = average out-degree of user's followees, C = number of eligible candidates. Space: O(C) for the scores dict.
Why this is correct
- Snapshot isolation: each snapshot is an independent deep copy. Mutations to
currentafter a snapshot cannot affect it. - Recommendation eligibility: only users reachable via at least one friend-of-friend path accumulate a score. Users with no such path are never added to
scoresand are therefore never returned. - Determinism: the sort key
(-score, id)is a total order, so the output is reproducible regardless of dict iteration order.
Complexity summary
| Operation | Time | Space |
|---|---|---|
| follow / unfollow | O(1) avg | O(1) |
| snapshot | O(E) | O(E) |
| is_following | O(1) avg | O(1) |
| following | O(d log d) | O(d) |
| recommend | O(F·D + C log C) | O(C) |
Full reference solution
from typing import List
def run_graph_operations(operations: List[str], arguments: List[List[int]]) -> List[object]:
# live adjacency map: user -> set of users they currently follow
current = {}
# one frozen copy of current per snapshot() call; index == snapshot id
snapshots = []
results = []
for operation, args in zip(operations, arguments):
if operation == "follow":
follower, followee = args
if follower != followee: # self-follows are silently ignored
current.setdefault(follower, set()).add(followee)
results.append(None)
elif operation == "unfollow":
follower, followee = args
current.get(follower, set()).discard(followee) # no-op if absent
results.append(None)
elif operation == "snapshot":
# deep-copy every live set so future mutations cannot touch this snapshot
snapshots.append({u: set(fs) for u, fs in current.items()})
results.append(len(snapshots) - 1)
elif operation == "is_following":
follower, followee, snapshot_id = args
results.append(followee in snapshots[snapshot_id].get(follower, set()))
elif operation == "following":
follower, snapshot_id = args
results.append(sorted(snapshots[snapshot_id].get(follower, set())))
elif operation == "recommend":
user, k = args
followed = current.get(user, set())
# accumulate friend-of-friend scores
scores = {}
for followee in followed:
for candidate in current.get(followee, set()):
if candidate != user and candidate not in followed:
scores[candidate] = scores.get(candidate, 0) + 1
# only users in `scores` are eligible (score >= 1 guaranteed)
ranked = sorted(scores, key=lambda c: (-scores[c], c))
results.append(ranked[:max(0, k)])
else:
raise ValueError(f"unknown operation: {operation}")
return results