Social Network / Follow Graph
Medium · Coding · 60 min
Design a follow graph data structure for a social network. Follow relationships are directed: A -> B means user A follows user B. The problem has 4 parts with incremental requirements.
Part 1: Timestamped Follows and Point-in-Time Queries
Implement FollowGraph:
update(a, b, t): At timestampt, userastarts following userb.check(a, b, t) -> bool: Returns whetherais followingbat timestampt.
Conventions:
- Timestamp
tis an integer;updatetakes effect inclusively att, socheck(a, b, t)isTrue. - Self-follows (
a == b) are a no-op, and redundant follows are also a no-op. - Events may arrive out of chronological order (e.g., an event at
t = 5arrives before an event att = 1), and queries are evaluated according to event time.
g = FollowGraph()
g.update("A", "B", 10)
g.check("A", "B", 9) # False
g.check("A", "B", 10) # True
g.check("B", "A", 99) # False: follow edges are directed
Part 2: Unfollow and Follower/Following Lists
unfollow(a, b, t): At timestampt,aunfollowsb.amay followbagain at a later timestamp.- If multiple events arrive for the exact same
(a, b, t), the later-arriving call overwrites the earlier one (last write wins). following(a, t) -> list[str]: All users whomais following at timestampt, sorted lexicographically.followers(b, t) -> list[str]: All users followingbat timestampt, sorted lexicographically.
Part 3: Two-Hop Recommendations
recommend(a, t, k=None) -> list[str]:
- Candidates are users followed at timestamp
tby the intermediaries whomafollows at timestampt. - Exclude
aitself and anyoneais already following directly at timestampt. - Ranking order:
- Higher number of intermediaries first;
- Ties broken by the most recent current follow-start timestamp among those intermediaries toward the candidate (larger timestamp first);
- Remaining ties broken lexicographically by user ID.
- When
kis notNone, return at most the topkcandidates.
A->B, B->C, B->D, A->M, M->C (all at t=1)
recommend("A", 10) == ["C", "D"] # C is reached via two intermediaries (B and M)
Part 4: Immutable Snapshots (Common Variant)
Instead of explicit timestamps, support point-in-time immutable snapshots:
class SocialNetwork:
def add_user(self, user_id): ... # existing user -> ValueError
def follow(self, follower, followee): ... # unknown user -> ValueError; self/duplicate follow is a no-op
def create_snapshot(self) -> "Snapshot": ...
class Snapshot:
def is_following(self, follower, followee) -> bool: ...
def get_following(self, user_id) -> list[str]: ... # lexicographical order
def get_followers(self, user_id) -> list[str]: ... # lexicographical order
def recommend(self, user_id, k) -> list[str]: ... # 2-hop count desc, then user_id asc
Calls to follow() after create_snapshot() must never mutate existing Snapshot instances.
Clarifying Questions to Ask in an Interview
- Are follow edges directed, and how should multiple events at the exact same timestamp be resolved?
- What is the tie-breaking rule for recommendations, and should already-followed users and self be excluded?
- What is the expected graph scale, and is
unfollowrequired?
Step-by-step walkthrough
Part 1 · Understand the problem: every directed edge has its own timeline
Follow relationships are directed (
A -> BmeansAfollowsB, not the other way around), events can arrive out of order, andcheck(a, b, t)asks about any historical timestampt. That means we cannot store just a singleTrue/Falseflag per pair(a, b)— we need to keep the timeline of events on that directed edge:Timeline on edge A -> B: t=1 follow t=5 unfollow t=8 follow check(A, B, 0) -> no events with time <= 0 -> False check(A, B, 4) -> events <= 4: [t=1 follow] -> True check(A, B, 6) -> events <= 6: [t=1 follow, t=5 unfollow] -> FalseOur core rule is one sentence: walk the events on
(a, b)in chronological order up tot, and the state after the last event<= tis the answer. Out-of-order arrivals stop being scary because we sort by timestamp at query time.Part 1 · Store `{timestamp: is_follow}` for each `(a, b)` pair
Let
self.events[(a, b)]be a dictionary mappingtimestamp -> bool, whereTruemeans follow andFalse(in Part 2) means unfollow.Using a dictionary per
(a, b)pair gives us two clean properties right away: 1. Checkingif a == b: returnignores self-follows in one line. 2. Assigningself.events[(a, b)][t] = is_followoverwrites any previous value at the exact same(a, b, t), which will automatically satisfy Part 2's "later-arriving call overwrites earlier call" rule!class FollowGraph: def __init__(self): # events: maps directed pair (follower, followee) -> dict {timestamp: is_follow_bool} self.events = {} def record(self, a: str, b: str, t: int, is_follow: bool) -> None: if a == b: return if (a, b) not in self.events: self.events[(a, b)] = {} self.events[(a, b)][t] = is_follow def update(self, a: str, b: str, t: int) -> None: self.record(a, b, t, True)Part 1 · Implement `check` by replaying timestamps `<= t`
To answer
check(a, b, t), look up the history dictionary for(a, b)(defaulting to{}if they have never interacted), iterate throughsorted(history), stop as soon asevent_time > t, and track the latest boolean state.def check(self, a: str, b: str, t: int) -> bool: history = self.events.get((a, b), {}) currently_following = False for event_time in sorted(history): if event_time > t: break currently_following = history[event_time] return currently_following✅ Submit now — Part 1 tests should pass.
Part 2 · Add `unfollow`, `following`, and `followers`
Because
recordalready stores a boolean atself.events[(a, b)][t],unfollow(a, b, t)is a one-liner that recordsFalse. And when two events hit the exact same(a, b, t), dictionary assignment overwrites the old boolean with the newly arrived one.For
following(a, t), scan all recorded edges(follower, followee)inself.events: wheneverfollower == aandself.check(follower, followee, t)isTrue, collectfolloweeand return the sorted list.followers(b, t)is symmetric, matchingfollowee == band collectingfollower.def unfollow(self, a: str, b: str, t: int) -> None: self.record(a, b, t, False) def following(self, a: str, t: int) -> list[str]: result = [] for follower, followee in self.events: if follower == a and self.check(follower, followee, t): result.append(followee) return sorted(result) def followers(self, b: str, t: int) -> list[str]: result = [] for follower, followee in self.events: if followee == b and self.check(follower, followee, t): result.append(follower) return sorted(result)✅ Submit now — Part 2 tests should pass.
Part 3 · Track when the current continuous follow streak started
Part 3's tie-breaker compares the start time of the intermediary's current follow streak toward the candidate. Look carefully at the difference between a duplicate follow and an unfollow-then-refollow:
Case 1 (duplicate follow): B -> Y: t=2 follow, t=4 follow (no-op!) --> at t=10, streak started at t=2 (NOT 4!) Case 2 (unfollow then refollow): B -> Y: t=2 follow, t=5 unfollow, t=7 follow --> at t=10, streak started at t=7We upgrade our timeline walk into
follow_start(a, b, t) -> int | None: - Whenis_followisTrue, we only setstart_time = event_timeifstart_time is None(transitioning from not-following to following). Ifstart_timeis already an integer, a duplicate follow leavesstart_timeuntouched! - Whenis_followisFalse, an unfollow resetsstart_time = None.Now
check(a, b, t)simply becomesself.follow_start(a, b, t) is not None!def follow_start(self, a: str, b: str, t: int) -> int | None: """If `a` is following `b` at time `t`, return when this continuous follow streak began; else None.""" history = self.events.get((a, b), {}) start_time = None for event_time in sorted(history): if event_time > t: break is_follow = history[event_time] if is_follow: if start_time is None: start_time = event_time else: start_time = None return start_time def check(self, a: str, b: str, t: int) -> bool: return self.follow_start(a, b, t) is not NonePart 3 · Rank 2-hop recommendations with tuple sorting
Let's trace who qualifies as a 2-hop candidate for user
aat timet:t=1 t=1 +-------> B +---------> C (reached via B and M -> count = 2) | | A + +---------> D (reached via B only -> count = 1) | +-------> M +---------> C- Find
direct_list = self.following(a, t)(the intermediariesb) and storedirect_set = set(direct_list)for fastO(1)exclusion checks. - For each intermediary
b, loop overcinself.following(b, t). Skipcifc == aorc in direct_set. Otherwise incrementintermediary_count[c]and updatelatest_start[c]withself.follow_start(b, c, t). - To sort by (1) highest count first, (2) latest start time first, (3) alphabetical ID
cfirst, build tuples(-intermediary_count[c], -latest_start[c], c)and call.sort(). Negating the two numbers flips Python's ascending sort into descending order while keepingcalphabetical!
def recommend(self, a: str, t: int, k: int | None = None) -> list[str]: if k is not None and k <= 0: return [] direct_list = self.following(a, t) direct_set = set(direct_list) intermediary_count = {} latest_start = {} for b in direct_list: for c in self.following(b, t): if c == a or c in direct_set: continue start_time = self.follow_start(b, c, t) intermediary_count[c] = intermediary_count.get(c, 0) + 1 if c not in latest_start or start_time > latest_start[c]: latest_start[c] = start_time sort_rows = [] for c in intermediary_count: sort_rows.append((-intermediary_count[c], -latest_start[c], c)) sort_rows.sort() ranked = [] for row in sort_rows: ranked.append(row[2]) if k is not None: ranked = ranked[:k] return ranked✅ Submit now — Part 3 tests should pass.
- Find
Part 4 · Build `SocialNetwork` with an adjacency dictionary
Part 4 switches to a second common interview variant: no timestamps, just live mutations plus immutable point-in-time snapshots. In
SocialNetwork, storeself.followingmapping each registereduser_idto asetof users they follow.Check both users exist in
self.followingbefore ignoringfollower == followee, so callingfollow("unknown", "unknown")still raisesValueErroras required.class SocialNetwork: def __init__(self): # following: maps user_id -> set of followee user_ids self.following = {} def add_user(self, user_id: str) -> None: if user_id in self.following: raise ValueError(f"user already exists: {user_id}") self.following[user_id] = set() def follow(self, follower: str, followee: str) -> None: if follower not in self.following or followee not in self.following: raise ValueError("unknown user") if follower != followee: self.following[follower].add(followee) def create_snapshot(self) -> "Snapshot": return Snapshot(self.following)Part 4 · Isolate `Snapshot` by copying every inner set
Why isn't
self.following = dict(following)enough insideSnapshot.__init__? Becausedict(following)is a shallow copy: it creates a new outer dictionary, but both dictionaries still point to the exact same innersetobjects!Shallow copy bug: Correct copy (copy every inner set): SocialNetwork.following["A"] --+ SocialNetwork.following["A"] --> {"B", "C", "F"} v {"B", "C", "F"} ^ Snapshot.following["A"] -------+ Snapshot.following["A"] -------> {"B", "C"} (future follow("A","F") leaks in!) (completely isolated!)Copying each user's set with
set(followees)freezes the snapshot completely. All four snapshot query methods then read from that frozen dictionary.class Snapshot: def __init__(self, following: dict[str, set[str]]): self.following = {} for user_id, followees in following.items(): self.following[user_id] = set(followees) def is_following(self, follower: str, followee: str) -> bool: return followee in self.following.get(follower, set()) def get_following(self, user_id: str) -> list[str]: return sorted(self.following.get(user_id, set())) def get_followers(self, user_id: str) -> list[str]: result = [] for candidate_follower, followees in self.following.items(): if user_id in followees: result.append(candidate_follower) return sorted(result) def recommend(self, user_id: str, k: int) -> list[str]: if k <= 0: return [] direct_set = self.following.get(user_id, set()) intermediary_count = {} for b in direct_set: for c in self.following.get(b, set()): if c != user_id and c not in direct_set: intermediary_count[c] = intermediary_count.get(c, 0) + 1 sort_rows = [] for c in intermediary_count: sort_rows.append((-intermediary_count[c], c)) sort_rows.sort() ranked = [] for row in sort_rows[:k]: ranked.append(row[1]) return ranked✅ Submit now — all tests should pass.
Intuition & how it works
Think of every one-way relationship A -> B in a directed graph (a network of users connected by one-way arrows, where A following B does not mean B follows A) as having its own light-switch logbook: whenever A follows or unfollows B, we write down (timestamp, ON/OFF) in (A, B)'s logbook. To answer whether A was following B at any historical moment t, we simply read (A, B)'s logbook in chronological order up to t and see where the switch ended up. Once we can ask who anyone followed at time t, 2-hop recommendations ("friends of friends" — candidates C reached in two steps A -> B -> C through an intermediary B whom A follows) are just counting how many intermediaries point to each candidate C at time t. And in Part 4, creating an immutable snapshot works like photocopying every page of an adjacency list (a dictionary mapping each user to the set of users they follow) rather than handing out a link to the live binder.
Why do simpler shortcuts fail? Storing only a current boolean or current set per user cannot answer historical check(a, b, t) queries and corrupts the graph whenever an older timestamp arrives after a newer one. In Part 3, recording the most recent update call instead of the start of the current continuous follow streak breaks ties whenever someone calls update twice in a row without an unfollow in between. And in Part 4, copying the graph with dict(self.following) performs a shallow copy (duplicating only the outer dictionary while sharing the mutable inner set objects), allowing future follow() calls to silently mutate old snapshots, whereas a deep copy of the sets duplicates every inner set so each snapshot stays frozen.
Let's trace a tiny Part 3 tie-breaking example at t = 10 after A -> B (t = 1), B -> X (t = 2), B -> Z (t = 4), and B -> Y (t = 7):
Step 1: A's direct followees at t=10 -> direct_list = ["B"]
Step 2: B's followees at t=10 -> "X" (streak start 2), "Y" (start 7), "Z" (start 4)
Step 3: Build sort tuples (-count, -latest_start, candidate_id):
"X" -> (-1, -2, "X")
"Y" -> (-1, -7, "Y")
"Z" -> (-1, -4, "Z")
Step 4: Ascending tuple sort -> [(-1, -7, "Y"), (-1, -4, "Z"), (-1, -2, "X")]
Result: ["Y", "Z", "X"] (for k=2, slice [:2] -> ["Y", "Z"])
Complexity
Let E be the number of distinct (follower, followee) pairs with recorded events (or active edges in Part 4), e be the maximum number of timestamped events on a single pair, F be the number of users a follows, C be the number of 2-hop candidates, and U be the number of users in SocialNetwork.
FollowGraph(Parts 1–3):updateandunfollow: TimeO(1)average, because dictionary lookup and assignment on(a, b)and timestamptareO(1)hash-table operations. SpaceO(N_events)total across all recorded events.checkandfollow_start: TimeO(e log e)and SpaceO(e), because we sort theetimestamps recorded on that single pair(a, b)and scan them once.followingandfollowers: TimeO(E + E * e log e + F log F)and SpaceO(F + e), because we scan allErecorded pairs inself.events, evaluatecheckon pairs matching usera(orb), and sort theFmatched user IDs alphabetically.recommend: TimeO((F + 1) * (E + E * e log e) + C log C)and SpaceO(F + C + e), because we callfollowingonce foraand once for each ofa'sFintermediaries, look upfollow_startfor each 2-hop edge, and sort theCcandidate tuples.
SocialNetworkandSnapshot(Part 4):add_userandfollow: TimeO(1)average using hash-dict and hash-set operations; SpaceO(U + E)for the entire network.create_snapshot: TimeO(U + E)and SpaceO(U + E), because we visit every one of theUusers and copy allEfollow edges into fresh inner sets.- Snapshot queries:
is_followingisO(1)average (hash-set membership);get_followingisO(F log F)(sortingFfollowees);get_followersisO(U + F_in log F_in)(checkinguser_id in followeesinO(1)acrossUusers, then sorting);recommendisO(F * G + C log C)whereGis the average number of followees per intermediary.
Edge cases
- Query timestamp earlier than the first event: The loop in
follow_startbreaks immediately and returnsNone, socheckreturnsFalse. - Query timestamp equal to an event timestamp: Because we only break when
event_time > t, an event atttakes effect attitself (check("A", "B", 10)afterupdate("A", "B", 10)isTrue). - Multiple events on the same
(a, b, t):self.events[(a, b)][t] = is_followoverwrites the prior boolean, so the last call received wins. - Self-follow (
a == b): Ignored inFollowGraph.recordandSocialNetwork.follow(after validating that the user exists inSocialNetwork). - Mutual follow (
A -> BandB -> A) duringrecommend("A", ...):B's followee"A"is explicitly skipped byif c == a or c in direct_set, so"A"is never recommended to itself. - Duplicate follow without an intervening unfollow:
if start_time is None: start_time = event_timekeeps the original streak start timestamp rather than overwriting it with the duplicate follow's timestamp. k = 0ork = Noneork > len(ranked):k = 0returns[],k = Nonereturns all ranked candidates, and Python list slicingranked[:k]safely returns all candidates whenkexceeds the list length.
Common mistakes
- Processing events in arrival order instead of timestamp order: Appending
(t, state)to a list and reading the last element breaks whenever historical updates arrive out of order. - Writing
else: start_time = Noneafterif is_follow and start_time is None:: If you write a single combinedif is_follow and start_time is None: ... else: start_time = None, then a duplicateupdate(is_follow == Truewhilestart_timeis already set) falls intoelseand falsely unfollows the user! Keepif is_follow:andelse:as separate outer branches. - Shallow-copying
self.followinginSnapshot.__init__: Writingself.following = self.following.copy()ordict(following)shares the innersetobjects withSocialNetwork, failing snapshot isolation as soon asfollow()is called afterward. - Forgetting to check user existence before the self-follow check in
SocialNetwork.follow:follow("ghost", "ghost")must raiseValueError, not silently succeed as a self-follow no-op. - Sorting tuple keys without negating counts and timestamps: Python sorts tuples in ascending order; forgetting the minus signs in
(-intermediary_count[c], -latest_start[c], c)puts the worst recommendations first.
Follow-up questions
- How can we speed up
following,followers, andcheckwhenEandeare large? Add two ever-growing adjacency indexesout_neighbors[a](everybthatahas ever interacted with) andin_neighbors[b](everyathat has ever interacted withb) sofollowing(a, t)only inspectsa's own edges instead of allEpairs. And if events arrive mostly in order (or we maintain sorted(timestamp, streak_start)intervals per edge), binary search (repeatedly halving a sorted array to find the last entry<= tinO(log e)steps viabisect_right) replaces theO(e log e)sort. - How can we make
create_snapshot()faster thanO(U + E)on a massive graph? Use copy-on-write (CoW) (sharing immutable inner data structures betweenSocialNetworkandSnapshotat zero copy cost, and replacing a user's set with a new copy only whenfollow()actually modifies that specific user), or unify Part 4 into Part 1 by assigning eachfollow()an auto-incrementing version numbervand storingSnapshot(version=v). - How do we handle celebrity nodes with 50 million followees/followers at scale? Partition edges across shards by
follower_id(forfollowing) andfollowee_id(forfollowers), cap or precompute 2-hop expansions offline in batch jobs, and maintain a bounded min-heap of sizek(O(C log k)) instead of sorting allCcandidates.
More OpenAI problems
- Infection Spread / Cellular Automata
- GPU Credits / GPU Credit 2
- Poker Simulation
- Classifier with Noisy Annotators
- Durable Key-Value Store Serialization
- NumPy Puzzle: 1-NN Vectorization → Wx+b Network
- Memory Allocator
- Transformer Bug Hunt
- Distributed Machine Cluster Count and Topology
- Autograd / Manual Backprop + Hillis-Steele Scan