KatInterview

Versioned Network Edge Tracker

Data Structure DesignAuto-graded · 18 test cases
MediumAuto-gradedData Structure Designdesign-dsarraystrees-graphs

Last updated

Process a stream of edge insertions, snapshot triggers, and historical adjacency queries for a dynamic graph.

Design an efficient data structure for tracking directed relationships in a dynamic graph over time. The system receives a sequence of command instructions and must record graph modifications, take versioned snapshots, and answer historical queries.

The commands are specified via two parallel lists: operations (strings indicating command names) and arguments (lists of integer parameters corresponding to each command).

The supported operations are:

  • "follow": Takes two integers [follower_id, followee_id]. Adds a directed edge from follower_id to followee_id. If this edge already exists in the active state, the command has no effect. Returns None (represented as None in Python).
  • "take_snapshot": Takes an empty argument list []. Assigns a unique, monotonically increasing snapshot ID starting from 0 for the first call, 1 for the second, and so on. Returns the newly generated integer snapshot ID.
  • "get_follows": Takes two integers [user_id, snapshot_id]. Queries the set of outbound edges for user_id at the moment snapshot_id was captured. Returns a sorted list of integers representing the followees.

Behavior and Edge Case Rules

  • If snapshot_id is invalid (e.g., negative or $\ge$ the total number of snapshots taken so far), return an empty list [].
  • If user_id had no outbound edges at the specified snapshot, return an empty list [].
  • Self-loops (a user following themselves) are allowed.
  • Queries can only inspect previously captured snapshots; active un-snapshotted state cannot be queried via "get_follows".

Constraints

  • $1 \le \text{len}(operations) \le 10^5$
  • arguments[i] matches the expected parameters for operations[i].
  • All user IDs are non-negative integers fitting in standard integer types.
  • Unrecognized operations will not occur.

Examples

Example 1

Input: social_graph_snapshots(['follow', 'take_snapshot', 'follow', 'take_snapshot', 'get_follows', 'get_follows'], [[1, 2], [], [1, 3], [], [1, 0], [1, 1]])

Output: [None, 0, None, 1, [2], [2, 3]]

Example 2

Input: social_graph_snapshots(['take_snapshot', 'get_follows', 'follow', 'take_snapshot', 'get_follows'], [[], [9, 0], [4, 4], [], [4, 1]])

Output: [0, [], None, 1, [4]]

Hints

Hint 1

Creating a full deep copy of the graph at every snapshot is too slow and memory-intensive.

Hint 2

Notice that snapshot IDs are sequential integers (0, 1, 2, ...). Can you tag each newly added edge with the snapshot version active when it was created?

Hint 3

Store the timeline of added edges per user in append-only lists. Since versions only increase, binary search (`bisect_right`) can quickly find all edges created on or before a target snapshot.