Fuse Two Sensor Pipelines Into One Object History Log
Data Structure DesignAuto-graded · 14 test casesLast updated
Simulate a tracker that links IDs across two systems, stores observations, and returns time-ordered merged histories, testing union-find style grouping and operation replay.
Fusing Two Sensor Pipelines
Two independent pipelines, System A and System B, each follow physical objects and give them their own identifiers. The same real-world object therefore usually has one ID in System A and a different ID in System B. Both pipelines produce observations. Each observation is a dictionary with these keys:
timestamp: a number giving when the observation was made,source: either"A"or"B", the pipeline that produced it,source_id: that pipeline's ID for the object,metadata: arbitrary data attached to the observation, which must be returned untouched.
You must simulate a tracker that supports three operations:
addLink(a_id, b_id): declares that System A's objecta_idand System B's objectb_idare the same physical object.addObservation(observation): stores one observation, from either system.getHistory(system, id): returns every observation belonging to the physical object thatiddenotes withinsystem("A"or"B").
Your task
Implement a function that receives a list of operation names and a parallel list of argument lists, runs the operations in order, and returns one result per operation.
operations[i]is one of"addLink","addObservation","getHistory".arguments[i]is the argument list for that operation:addLink:[a_id, b_id]addObservation:[observation](a list holding one dictionary)getHistory:[system, id]
The result list has the same length as operations:
- for
addLinkandaddObservation, the entry isNone; - for
getHistory, the entry is a list of observation dictionaries.
Rules
- Identity is transitive. Links connect IDs into groups. If
a1is linked tob1, andb1is linked toa2, thena1,b1anda2all denote one physical object. An ID may be linked multiple times, and repeating a link has no further effect. An A-ID and a B-ID with the same text are different identities (("A", "x")is not("B", "x")) unless linked. - Order of operations matters, but links apply retroactively. A link may arrive after observations for its IDs were stored. A later
getHistorymust include all observations stored so far for every ID in the merged group, regardless of when the link was added. AgetHistoryonly reflects operations before it. - History contents. The history for a group contains every observation stored so far under any ID of the group, from both systems. Each returned observation keeps its
timestamp,source,source_idandmetadataexactly as it was added. - Ordering. Sort by
timestampascending. If two observations have equal timestamps, the one that was added earlier (byaddObservationcall order) comes first. - Unknown IDs. If the queried
(system, id)has never appeared in any link or observation so far, return an empty list. If it has appeared but has no observations in its group, also return an empty list. - Links are never removed or changed.
Constraints
1 <= len(operations) == len(arguments) <= 10^4- IDs are strings;
systemandsourceare always"A"or"B". - Timestamps are numbers (integers or floats); they may arrive out of order and may repeat.
metadatacan be any JSON-like value.- Each observation is added at most once per
addObservationcall; the same content may be added multiple times and each addition counts as a separate observation.
Examples
Example 1
Input: fuse_object_histories(['addObservation', 'addObservation', 'addLink', 'getHistory'], [[{'timestamp': 2, 'source': 'A', 'source_id': 'a1', 'metadata': {'x': 1}}], [{'timestamp': 1, 'source': 'B', 'source_id': 'b1', 'metadata': {'y': 2}}], ['a1', 'b1'], ['A', 'a1']])
Output: [None, None, None, [{'timestamp': 1, 'source': 'B', 'source_id': 'b1', 'metadata': {'y': 2}}, {'timestamp': 2, 'source': 'A', 'source_id': 'a1', 'metadata': {'x': 1}}]]
Example 2
Input: fuse_object_histories(['addLink', 'addObservation', 'getHistory'], [['a1', 'b1'], [{'timestamp': 5, 'source': 'B', 'source_id': 'b1', 'metadata': 'car'}], ['B', 'b1']])
Output: [None, None, [{'timestamp': 5, 'source': 'B', 'source_id': 'b1', 'metadata': 'car'}]]
Hints
Hint 1
Treat each (system, id) pair as a node. Linking two IDs merges their groups, and a group is exactly one physical object. A disjoint-set (union-find) structure handles chains of links well.
Hint 2
Store each observation under its own (source, source_id) node together with an increasing counter of when it was added. Then a late link does not require rewriting anything: at query time, gather observations from all nodes whose root matches.
Hint 3
For getHistory, find the root of the queried node, collect the entries of all nodes sharing that root, and sort by (timestamp, insertion counter). Return an empty list if the node was never seen.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each (system, id) pair is a node in a disjoint-set (union-find) structure. addLink unions the node ("A", a_id) with ("B", b_id), so any chain of links collapses into one group, which represents one physical object.
Observations are not copied into a merged record. Each one is stored in a dictionary keyed by its own node (source, source_id), together with a global insertion counter. This keeps every observation's original source, ID and metadata intact.
For getHistory(system, id):
- If the node has never been seen (no link and no observation mentioned it), return
[]. - Find the root of the node.
- Walk through all nodes that hold observations, and keep the entries of those whose root equals the query root.
- Sort the collected entries by
(timestamp, insertion counter). The counter gives the required tie-break: earlier-added first on equal timestamps. - Return the observation dictionaries.
Why it is correct
Union-find maintains exactly the transitive closure of the links, so two IDs share a root if and only if a chain of links connects them. Since observations are grouped by root only at query time, a link added after observations still includes them in later queries, and a query never sees later operations. Sorting on (timestamp, counter) is a total order that matches the stated tie rule.
Complexity
Let n be the number of operations, m the number of stored observations, and k the number of distinct nodes holding observations.
addLink: amortized near O(α(n)) (inverse Ackermann) with path compression and union by rank.addObservation: O(α(n)) amortized for the find, plus O(1) to append.getHistory: O(k · α(n) + r log r), whereris the size of the returned history. The worst case is O(m log m).- Space: O(n + m).
A more query-optimized variant would keep a per-group list and merge lists on union (small-to-large), making queries cost only O(r log r) or O(r) with sorted merges, at the price of heavier link operations.
Reference solution
from typing import Dict, List
def fuse_object_histories(operations: List[str], arguments: List[List]) -> List[List[Dict]]:
parent = {}
rank = {}
observations = {}
results = []
sequence = 0
def find(node):
if node not in parent:
parent[node] = node
rank[node] = 0
return node
if parent[node] != node:
parent[node] = find(parent[node])
return parent[node]
def union(left, right):
root_left = find(left)
root_right = find(right)
if root_left == root_right:
return
if rank[root_left] < rank[root_right]:
root_left, root_right = root_right, root_left
parent[root_right] = root_left
if rank[root_left] == rank[root_right]:
rank[root_left] += 1
for operation, args in zip(operations, arguments):
if operation == "addLink":
a_id, b_id = args
union(("A", a_id), ("B", b_id))
results.append(None)
elif operation == "addObservation":
observation = dict(args[0])
source = observation["source"]
source_id = observation["source_id"]
node = (source, source_id)
find(node)
observations.setdefault(node, []).append((sequence, observation))
sequence += 1
results.append(None)
elif operation == "getHistory":
system, object_id = args
node = (system, object_id)
if node not in parent:
results.append([])
continue
root = find(node)
entries = []
for other_node, items in observations.items():
if find(other_node) == root:
entries.extend(items)
entries.sort(key=lambda item: (item[1]["timestamp"], item[0]))
results.append([item[1] for item in entries])
else:
raise ValueError("Unknown operation")
return results