Versioned Network Edge Tracker
Data Structure DesignAuto-graded · 18 test casesLast 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 fromfollower_idtofollowee_id. If this edge already exists in the active state, the command has no effect. ReturnsNone(represented asNonein Python)."take_snapshot": Takes an empty argument list[]. Assigns a unique, monotonically increasing snapshot ID starting from0for the first call,1for 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 foruser_idat the momentsnapshot_idwas captured. Returns a sorted list of integers representing the followees.
Behavior and Edge Case Rules
- If
snapshot_idis invalid (e.g., negative or $\ge$ the total number of snapshots taken so far), return an empty list[]. - If
user_idhad 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 foroperations[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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A naive implementation might clone the entire adjacency list whenever take_snapshot is called. However, copying the graph takes time and memory proportional to the total number of edges per snapshot, which is inefficient.
Instead of copying the full state, we maintain a history of additions per user tagged with a version counter (the current number of snapshots taken):
- Version Tracking: Maintain a integer counter
versioninitialized to0. Each call totake_snapshotreturnsversionand increments it by1. - Per-User History: For each user, track two parallel lists:
versions[u]: the version counter value when each followee was added.followees[u]: the ID of the followee corresponding to that entry.
- Deduplication: Maintain a set
seen[u]for each user. Iffollowee_idis already inseen[follower_id], ignore the operation to preserve set semantics. - Querying History: To evaluate
get_follows(u, snapshot_id):- Verify that
0 <= snapshot_id < version. If invalid, return[]. - Since additions occur chronologically,
versions[u]is always sorted. - Use
bisect_right(versions[u], snapshot_id)to find the number of followees added on or beforesnapshot_id. - Slice
followees[u][:i]and return it sorted.
- Verify that
Complexity
follow: $O(1)$ amortized time per call to add to sets and append to history.take_snapshot: $O(1)$ time.get_follows: $O(\log H + M \log M)$ time, where $H$ is the total history size for useruand $M$ is the number of active followees atsnapshot_id.- Space Complexity: $O(V + E)$ total memory across all operations, where $V$ is the number of unique users and $E$ is the total number of distinct edges created.
from typing import List
from bisect import bisect_right
def social_graph_snapshots(operations: List[str], arguments: List[List[int]]) -> List[object]:
versions = {}
followees = {}
seen = {}
version = 0
results = []
for operation, args in zip(operations, arguments):
if operation == "follow":
follower_id, followee_id = args
s = seen.setdefault(follower_id, set())
if followee_id not in s:
s.add(followee_id)
versions.setdefault(follower_id, []).append(version)
followees.setdefault(follower_id, []).append(followee_id)
results.append(None)
elif operation == "take_snapshot":
results.append(version)
version += 1
elif operation == "get_follows":
user_id, snapshot_id = args
if 0 <= snapshot_id < version and user_id in versions:
i = bisect_right(versions[user_id], snapshot_id)
results.append(sorted(followees[user_id][:i]))
else:
results.append([])
else:
raise ValueError("Unknown operation")
return results