Versioned Follow Graph with Time-Travel Queries and Suggestions
Data Structure DesignModel answerLast updated
Build an in-memory directed follow graph with cheap snapshots, historical edge lookups, and a friends-of-friends suggestion ranking with id tie-breaks.
Versioned Follow Graph
Build an in-memory component that tracks who follows whom among users numbered 1..N. N may be very large, so memory must not scale with N. The component must also answer questions about earlier states of the graph and suggest accounts to follow.
Implement these operations:
follow(u, v):ustarts followingv.unfollow(u, v):ustops followingv.snap() -> sid: freeze the current graph and return a snapshot id. Ids increase monotonically.isFollowing(u, v, sid) -> bool: wasufollowingvat the moment snapshotsidwas taken?recommend(u, k) -> list[int]: return up tokaccounts foruto follow.- Candidates must not be
uand must not be accountsucurrently follows. - A candidate's score is the number of accounts that
ucurrently follows that also follow the candidate. - Sort by score descending, then by user id ascending.
- Candidates must not be
Rules to handle
- Edges are directed.
ufollowingvsays nothing aboutvfollowingu. - A repeated
followof an existing edge, or anunfollowof a missing edge, changes nothing. - A user cannot follow themselves, so
follow(u, u)is ignored. - Snapshots are immutable. Later changes never alter the answer for an earlier
sid. recommenduses the current graph, not a snapshot, and only returns candidates with a score of at least 1.- Decide and state what happens when
sidhas not been issued yet.
What to deliver
Describe your data structures, implement the five operations, and analyze time and space. Pay particular attention to workloads with millions of mutations and many snapshots.
Example
follow(1, 2); follow(1, 3)
follow(2, 4); follow(3, 4); follow(3, 5)
s0 = snap() # 0
unfollow(1, 2)
s1 = snap() # 1
isFollowing(1, 2, s0) # True
isFollowing(1, 2, s1) # False
recommend(1, 5) # [4, 5] (4 via 3 only now; 5 via 3)
After unfollow(1, 2), user 1 follows only 3, so both 4 and 5 score 1 and the tie is broken by id.
Hints
Hint 1
Copying the whole graph on every snapshot costs O(edges x snapshots) memory. Think about recording only what changes, per edge, and tagging each change with a version.
Hint 2
For one edge (u, v), keep a list of (version, present?) entries in increasing version order. A historical query becomes 'find the last entry with version <= sid', which is a binary search. If several changes happen between two snaps, only the last one is observable, so you can overwrite instead of appending.
Hint 3
For recommendations, iterate over the accounts u follows, then over the accounts each of those follows, and count occurrences in a hash map while skipping u and existing followees. Then pick the top k with a heap keyed on (-count, id) instead of sorting everything.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach overview
Keep two views of the data:
- Current state: a map from each user to the set of users they follow. Only users who have at least one edge are stored, so memory is independent of
N. Sets give O(1) membership tests and fast iteration for suggestions. - Per-edge history: for each edge ever touched, a short log of how its presence changed across snapshot versions.
snap() never copies anything. It just advances a version counter.
Contract decisions to state up front
- Directed edges.
follow(u, v)is independent offollow(v, u). - No-ops. Duplicate follows, unfollows of absent edges, and self-follows do nothing and write no history.
- Snapshot ids. The first
snap()returns 0, the next 1, and so on.isFollowing(u, v, sid)reflects every mutation performed before the call tosnap()that returnedsid. - Unissued ids. A negative
sid, or one not yet returned bysnap(), raisesValueError. ReturningFalsewould also be acceptable if stated. - Recommendations use the current graph and return only candidates with a score of at least 1. Padding with zero-score users would require scanning all
Nusers, which is a poor idea whenNis large. It can be offered as a follow-up.
Versioning the edges
Maintain a counter version, equal to the id the next snap() will return. Every effective mutation is tagged with the current version. That tag means "this change is visible from snapshot version onward".
For an edge, the history is two parallel lists: tags (strictly increasing) and states (True = following). When the edge changes:
- If there is no history, or the last tag is smaller than
version, append(version, state). - If the last tag equals
version, overwrite the last state. Several toggles between two snapshots collapse into one entry, because only the final state is observable.
To answer isFollowing(u, v, sid):
- Validate
sid. - If the edge has no history, return
False. - Binary-search for the rightmost tag
<= sid. If none exists, the edge did not exist yet, so returnFalse. Otherwise return the state at that position.
Keeping tags in their own integer list lets bisect_right work directly without tuple tricks.
Why it is correct
A mutation made after the snapshot that returned sid is tagged sid + 1 or later, so it is never selected for sid. Every mutation made before that snapshot has a tag <= sid. The last such entry therefore holds the final state at the time of the snapshot. Strictly increasing tags make the binary search valid.
Recommendations
For user u with followee set F:
- For each
finF, for eachwinfollowing[f], ifw != uandw not in F, incrementcount[w]. - Each follow set holds an edge at most once, so
count[w]is the number of distinct followees ofuwho followw. - Select the top
kby key(-count, id)usingheapq.nsmallest, which is O(C log k) forCcandidates.
If k <= 0 or u follows nobody, return []. If fewer than k candidates exist, return them all.
Complexity
Let d(x) be the out-degree of x, h the history length of one edge, M the number of effective mutations, and C the number of distinct candidates.
| Operation | Time |
|---|---|
follow / unfollow | O(1) amortized |
snap | O(1) |
isFollowing | O(log h) |
recommend | O(sum of d(f) for f in F) + O(C log k) |
Space is O(current edges + M). It does not depend on the number of snapshots, so a million consecutive snap() calls with no changes cost nothing extra. Thanks to overwriting, each edge adds at most one history entry per snapshot interval in which it changed.
Code
from bisect import bisect_right
from collections import defaultdict
import heapq
class VersionedFollowGraph:
def __init__(self):
self._out = {} # user -> set of followees (current)
self._tags = {} # (u, v) -> increasing list of version tags
self._vals = {} # (u, v) -> list of bools, parallel to _tags
self._version = 0 # id the next snap() will return
def _log(self, u, v, present):
key = (u, v)
tags = self._tags.get(key)
if tags is None:
self._tags[key] = [self._version]
self._vals[key] = [present]
elif tags[-1] == self._version:
self._vals[key][-1] = present
else:
tags.append(self._version)
self._vals[key].append(present)
def follow(self, u, v):
if u == v:
return
s = self._out.setdefault(u, set())
if v in s:
return
s.add(v)
self._log(u, v, True)
def unfollow(self, u, v):
s = self._out.get(u)
if not s or v not in s:
return
s.remove(v)
self._log(u, v, False)
def snap(self):
sid = self._version
self._version += 1
return sid
def isFollowing(self, u, v, sid):
if sid < 0 or sid >= self._version:
raise ValueError("snapshot id has not been issued")
tags = self._tags.get((u, v))
if tags is None:
return False
i = bisect_right(tags, sid) - 1
return i >= 0 and self._vals[(u, v)][i]
def recommend(self, u, k):
if k <= 0:
return []
mine = self._out.get(u)
if not mine:
return []
counts = defaultdict(int)
for f in mine:
for w in self._out.get(f, ()):
if w != u and w not in mine:
counts[w] += 1
top = heapq.nsmallest(k, counts.items(), key=lambda kv: (-kv[1], kv[0]))
return [w for w, _ in top]
Edge cases
- Follow then unfollow within one snapshot interval leaves a single
Falseentry, so the edge is correctly absent at that snapshot. - An edge that never existed has no history key and returns
False. - A user who is followed back by their followees never gets themselves recommended, because
w != uis checked. - Read paths use
.getso that queries do not create empty entries.
Common mistakes
- Deep-copying the graph in
snap(), which blows up memory. - Tagging mutations with the id just returned instead of the id the next snap will return, which shifts every answer by one snapshot.
- Appending a new history entry per toggle instead of collapsing within an interval, which breaks the strictly increasing tag assumption and wastes space.
- Forgetting to exclude current followees or
ufrom candidates. - Sorting all candidates (O(C log C)) when a size-
kheap suffices.
Follow-ups to be ready for
- Answering
recommendagainst a historical snapshot. This needs the per-user follow set at versionsid, which can be reconstructed from per-edge histories, or by keeping per-user versioned adjacency with persistent sets. - Hot accounts with huge follower counts. Cap the fan-out per followee, sample, or precompute and cache counts.
- Compacting old history once old snapshot ids are no longer queryable.
- Padding results with zero-score users using a popularity list rather than a full scan.