Versioned Cache and Longest Dependency Chain
Data Structure DesignAuto-graded · 19 test casesLast updated
Process a series of timestamped key-value operations and find the longest non-cyclic path in a dependency graph.
You are tasked with evaluating two separate system component sub-modules: a time-travel key-value state evaluator and a longest dependency chain analyzer.
Component 1: Time-Travel Operations
You are given a sequence of operations (operations) and their corresponding positional arguments (arguments). Supported operations include:
"put":[key, value, timestamp]— Storesvalueforkeyattimestamp. If an entry exists attimestamp, overwrite it."delete":[key, timestamp]— Removeskeyattimestamp. Subsequent reads at or after this timestamp returnNone(tombstone) until a newer"put"is applied."get":[key, timestamp]— Returns the value ofkeyas oftimestamp. This corresponds to the write/delete entry with the largest timestamp $\le \text{timestamp}$. ReturnsNoneif no entry exists $\le \text{timestamp}$, or if the effective entry is a delete."scan":[prefix, timestamp]— Returns a list of all active keys (keys whose effective value attimestampis notNone) starting withprefix, ordered lexicographically.
For "put" and "delete", the return output is None. For "get" and "scan", the output is the evaluated result.
Component 2: Longest Dependency Path
Given a list of directed edges [u, v] (where v depends on u, establishing a directed edge $u \to v$) and a start_node:
- Find the longest path in the graph starting at
start_node. - If a cycle exists within the graph, return an empty list
[]. - If multiple paths tie for the maximum length, choose the lexicographically smallest path sequence.
- If
start_nodehas no outgoing edges, the path is[start_node].
Return a single list containing two items: [operations_results, longest_path].
Constraints
- $0 \le \text{len(operations)} \le 1000$
- Timestamps are positive integers.
- Keys, values, and node names are non-empty strings.
- Graphs may contain up to 5,000 nodes and directed edges.
- Node comparison for tie-breaking uses standard lexicographical string ordering.
Examples
Example 1
Input: evaluate_system_features(['put', 'put', 'get'], [['config', 'v1', 10], ['config', 'v2', 20], ['config', 15]], [], '')
Output: [[None, None, 'v1'], ['']]
Example 2
Input: evaluate_system_features([], [], [['A', 'B'], ['B', 'C'], ['A', 'C']], 'A')
Output: [[], ['A', 'B', 'C']]
Hints
Hint 1
For time-travel queries, maintain history maps per key and use binary search (bisect_right) on sorted timestamps to find floor entries.
Hint 2
A delete operation can be represented internally as setting a key's timestamp to None.
Hint 3
To find the longest path on a graph, detect cycles using Topological Sort (Kahn's Algorithm). If topological ordering fails to include all nodes, a cycle exists.
Hint 4
Using dynamic programming in reverse topological order allows efficiently computing the maximum length path and resolving lexicographical ties.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires solving two distinct parts:
-
Versioned Key-Value State Evaluator:
- For each operation, record changes in a map per key where timestamps are mapped to values or
None(representing tombstones). - For
getandscan, find the largest timestamp $\le t$ using binary search (bisect_right). - Filter active keys matching the prefix for
scanoperations and return them sorted lexicographically.
- For each operation, record changes in a map per key where timestamps are mapped to values or
-
Longest Dependency Path:
- Build a directed graph from the dependency edges and count in-degrees.
- Perform Kahn's algorithm (topological sort) using a min-heap or sorted queue to ensure deterministic node processing.
- If the topological sort does not process all graph nodes, a cycle is present; return
[]. - Process nodes in reverse topological order to compute the longest path dynamic programming state. For a node $u$, select among its children $v$ a path $p_v$ that maximizes length and breaks ties by choosing the lexicographically smallest tuple path sequence.
Complexity
- Part 1 Operations:
put/delete: $O(1)$ dictionary insertion.get: $O(V \log V)$ where $V$ is the number of version entries per key.scan: $O(K \cdot V \log V + M \log M)$ where $K$ is total keys and $M$ is matching active keys.
- Part 2 Path Reconstruction:
- Topological sort: $O(V + E \log V)$
- DP path selection: $O(V + E)$
- Overall Space: $O(K \cdot V + N + E)$ where $N, E$ are nodes and edges.
Solution
from bisect import bisect_right
from collections import defaultdict, deque
from typing import List
def evaluate_system_features(operations: List[str], arguments: List[List], edges: List[List[str]], start_node: str) -> List:
histories = defaultdict(dict)
results = []
for operation, args in zip(operations, arguments):
if operation == "put":
key, value, timestamp = args
histories[key][timestamp] = value
results.append(None)
elif operation == "delete":
key, timestamp = args
histories[key][timestamp] = None
results.append(None)
elif operation == "get":
key, timestamp = args
versions = histories.get(key, {})
times = sorted(versions)
index = bisect_right(times, timestamp) - 1
results.append(versions[times[index]] if index >= 0 else None)
elif operation == "scan":
prefix, timestamp = args
active = []
for key, versions in histories.items():
if not key.startswith(prefix):
continue
times = sorted(versions)
index = bisect_right(times, timestamp) - 1
if index >= 0 and versions[times[index]] is not None:
active.append(key)
results.append(sorted(active))
else:
raise ValueError("unknown operation")
graph = defaultdict(set)
nodes = {start_node}
indegree = defaultdict(int)
for u, v in edges:
nodes.add(u)
nodes.add(v)
if v not in graph[u]:
graph[u].add(v)
indegree[v] += 1
queue = deque(sorted(node for node in nodes if indegree[node] == 0))
order = []
while queue:
node = queue.popleft()
order.append(node)
for neighbor in sorted(graph[node]):
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
queue.append(neighbor)
if len(order) != len(nodes):
path = []
else:
best = {}
for node in reversed(order):
candidates = [best[neighbor] for neighbor in graph[node]]
if candidates:
best[node] = (node,) + min(candidates, key=lambda p: (-len(p), p))
else:
best[node] = (node,)
path = list(best[start_node])
return [results, path]