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 timestamp t, user a starts following user b.
  • check(a, b, t) -> bool: Returns whether a is following b at timestamp t.

Conventions:

  • Timestamp t is an integer; update takes effect inclusively at t, so check(a, b, t) is True.
  • 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 = 5 arrives before an event at t = 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 timestamp t, a unfollows b. a may follow b again 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 whom a is following at timestamp t, sorted lexicographically.
  • followers(b, t) -> list[str]: All users following b at timestamp t, sorted lexicographically.

Part 3: Two-Hop Recommendations

recommend(a, t, k=None) -> list[str]:

  • Candidates are users followed at timestamp t by the intermediaries whom a follows at timestamp t.
  • Exclude a itself and anyone a is already following directly at timestamp t.
  • Ranking order:
    1. Higher number of intermediaries first;
    2. Ties broken by the most recent current follow-start timestamp among those intermediaries toward the candidate (larger timestamp first);
    3. Remaining ties broken lexicographically by user ID.
  • When k is not None, return at most the top k candidates.
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 unfollow required?

Step-by-step walkthrough

  1. Part 1 · Understand the problem: every directed edge has its own timeline

    Follow relationships are directed (A -> B means A follows B, not the other way around), events can arrive out of order, and check(a, b, t) asks about any historical timestamp t. That means we cannot store just a single True/False flag 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]       -> False
    

    Our core rule is one sentence: walk the events on (a, b) in chronological order up to t, and the state after the last event <= t is the answer. Out-of-order arrivals stop being scary because we sort by timestamp at query time.

  2. Part 1 · Store `{timestamp: is_follow}` for each `(a, b)` pair

    Let self.events[(a, b)] be a dictionary mapping timestamp -> bool, where True means follow and False (in Part 2) means unfollow.

    Using a dictionary per (a, b) pair gives us two clean properties right away: 1. Checking if a == b: return ignores self-follows in one line. 2. Assigning self.events[(a, b)][t] = is_follow overwrites 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)
    
  3. 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 through sorted(history), stop as soon as event_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.

  4. Part 2 · Add `unfollow`, `following`, and `followers`

    Because record already stores a boolean at self.events[(a, b)][t], unfollow(a, b, t) is a one-liner that records False. 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) in self.events: whenever follower == a and self.check(follower, followee, t) is True, collect followee and return the sorted list. followers(b, t) is symmetric, matching followee == b and collecting follower.

    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.

  5. 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=7
    

    We upgrade our timeline walk into follow_start(a, b, t) -> int | None: - When is_follow is True, we only set start_time = event_time if start_time is None (transitioning from not-following to following). If start_time is already an integer, a duplicate follow leaves start_time untouched! - When is_follow is False, an unfollow resets start_time = None.

    Now check(a, b, t) simply becomes self.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 None
    
  6. Part 3 · Rank 2-hop recommendations with tuple sorting

    Let's trace who qualifies as a 2-hop candidate for user a at time t:

          t=1          t=1
      +-------> B +---------> C (reached via B and M -> count = 2)
      |           |
    A +           +---------> D (reached via B only  -> count = 1)
      |
      +-------> M +---------> C
    
    1. Find direct_list = self.following(a, t) (the intermediaries b) and store direct_set = set(direct_list) for fast O(1) exclusion checks.
    2. For each intermediary b, loop over c in self.following(b, t). Skip c if c == a or c in direct_set. Otherwise increment intermediary_count[c] and update latest_start[c] with self.follow_start(b, c, t).
    3. To sort by (1) highest count first, (2) latest start time first, (3) alphabetical ID c first, 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 keeping c alphabetical!
    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.

  7. 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, store self.following mapping each registered user_id to a set of users they follow.

    Check both users exist in self.following before ignoring follower == followee, so calling follow("unknown", "unknown") still raises ValueError as 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)
    
  8. Part 4 · Isolate `Snapshot` by copying every inner set

    Why isn't self.following = dict(following) enough inside Snapshot.__init__? Because dict(following) is a shallow copy: it creates a new outer dictionary, but both dictionaries still point to the exact same inner set objects!

    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):
    • update and unfollow: Time O(1) average, because dictionary lookup and assignment on (a, b) and timestamp t are O(1) hash-table operations. Space O(N_events) total across all recorded events.
    • check and follow_start: Time O(e log e) and Space O(e), because we sort the e timestamps recorded on that single pair (a, b) and scan them once.
    • following and followers: Time O(E + E * e log e + F log F) and Space O(F + e), because we scan all E recorded pairs in self.events, evaluate check on pairs matching user a (or b), and sort the F matched user IDs alphabetically.
    • recommend: Time O((F + 1) * (E + E * e log e) + C log C) and Space O(F + C + e), because we call following once for a and once for each of a's F intermediaries, look up follow_start for each 2-hop edge, and sort the C candidate tuples.
  • SocialNetwork and Snapshot (Part 4):
    • add_user and follow: Time O(1) average using hash-dict and hash-set operations; Space O(U + E) for the entire network.
    • create_snapshot: Time O(U + E) and Space O(U + E), because we visit every one of the U users and copy all E follow edges into fresh inner sets.
    • Snapshot queries: is_following is O(1) average (hash-set membership); get_following is O(F log F) (sorting F followees); get_followers is O(U + F_in log F_in) (checking user_id in followees in O(1) across U users, then sorting); recommend is O(F * G + C log C) where G is the average number of followees per intermediary.

Edge cases

  • Query timestamp earlier than the first event: The loop in follow_start breaks immediately and returns None, so check returns False.
  • Query timestamp equal to an event timestamp: Because we only break when event_time > t, an event at t takes effect at t itself (check("A", "B", 10) after update("A", "B", 10) is True).
  • Multiple events on the same (a, b, t): self.events[(a, b)][t] = is_follow overwrites the prior boolean, so the last call received wins.
  • Self-follow (a == b): Ignored in FollowGraph.record and SocialNetwork.follow (after validating that the user exists in SocialNetwork).
  • Mutual follow (A -> B and B -> A) during recommend("A", ...): B's followee "A" is explicitly skipped by if 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_time keeps the original streak start timestamp rather than overwriting it with the duplicate follow's timestamp.
  • k = 0 or k = None or k > len(ranked): k = 0 returns [], k = None returns all ranked candidates, and Python list slicing ranked[:k] safely returns all candidates when k exceeds 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 = None after if is_follow and start_time is None:: If you write a single combined if is_follow and start_time is None: ... else: start_time = None, then a duplicate update (is_follow == True while start_time is already set) falls into else and falsely unfollows the user! Keep if is_follow: and else: as separate outer branches.
  • Shallow-copying self.following in Snapshot.__init__: Writing self.following = self.following.copy() or dict(following) shares the inner set objects with SocialNetwork, failing snapshot isolation as soon as follow() is called afterward.
  • Forgetting to check user existence before the self-follow check in SocialNetwork.follow: follow("ghost", "ghost") must raise ValueError, 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, and check when E and e are large? Add two ever-growing adjacency indexes out_neighbors[a] (every b that a has ever interacted with) and in_neighbors[b] (every a that has ever interacted with b) so following(a, t) only inspects a's own edges instead of all E pairs. 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 <= t in O(log e) steps via bisect_right) replaces the O(e log e) sort.
  • How can we make create_snapshot() faster than O(U + E) on a massive graph? Use copy-on-write (CoW) (sharing immutable inner data structures between SocialNetwork and Snapshot at zero copy cost, and replacing a user's set with a new copy only when follow() actually modifies that specific user), or unify Part 4 into Part 1 by assigning each follow() an auto-incrementing version number v and storing Snapshot(version=v).
  • How do we handle celebrity nodes with 50 million followees/followers at scale? Partition edges across shards by follower_id (for following) and followee_id (for followers), cap or precompute 2-hop expansions offline in batch jobs, and maintain a bounded min-heap of size k (O(C log k)) instead of sorting all C candidates.

More OpenAI problems