Social follow graph with point-in-time snapshots
I was asked this
No reports yet. Sign in to say where you were asked it.
Build an in-memory follow graph that can answer questions about its own past. Follows are directed: a following b says nothing about b following a.
Implement a SocialNetwork class:
-
SocialNetwork()creates an empty graph. -
follow(follower: int, followee: int) -> Nonemakesfollowerfollowfolloweein the current working state. Following yourself, or following someone you already follow, does nothing. -
unfollow(follower: int, followee: int) -> Noneremoves that follow from the working state. Removing a follow that does not exist does nothing. -
snapshot() -> intfreezes the working state and returns its id. Ids start at 0 and go up by 1 with each call. -
is_following(follower: int, followee: int, snap_id: int) -> boolreturns whetherfollowerfollowedfolloweeat the moment snapshotsnap_idwas taken. Changes made after that snapshot do not affect the answer. Raise an error for an id that has not been returned bysnapshot().
Constraints
- Up to
10^5users and2 * 10^5calls in total. - Many snapshots may be taken with few or no changes between them, so copying the whole graph on each snapshot is too slow and uses too much memory.
- Aim for
O(1)follow,unfollowandsnapshot, andO(log n)is_following.
Example 1
g = SocialNetwork()
g.follow(10, 20)
g.follow(10, 30)
g.snapshot() -> 0
g.unfollow(10, 20)
g.follow(20, 10)
g.snapshot() -> 1
g.is_following(10, 20, 0) -> true
g.is_following(10, 20, 1) -> false
g.is_following(20, 10, 0) -> false
g.is_following(20, 10, 1) -> true
Example 2
g = SocialNetwork()
g.follow(4, 7)
g.unfollow(4, 7)
g.follow(4, 7)
g.snapshot() -> 0
g.snapshot() -> 1
g.unfollow(4, 7)
g.is_following(4, 7, 1) -> true # the unfollow came after snapshot 1
g.is_following(7, 4, 1) -> false # follows are directed
Be ready to extend the class: list a user's followees at a snapshot, then recommend accounts to follow based on the graph at a snapshot.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.

