Unified Entity Log with Mergeable ID Groups
Data Structure DesignAuto-graded · 20 test casesLast updated
Tests ability to design a data structure that resolves multiple system-assigned IDs to a single entity and returns a chronologically merged observation history.
Problem
A fleet of sensors — cameras, radar units, laser scanners, and others — each assign their own local IDs to the physical objects they detect. The same car driving past might be called "C-1" by a camera and "R-5" by a radar unit. Your job is to build a data structure that keeps a unified observation log for each physical entity, even as new ID equivalences are discovered over time.
Implement a function run_entity_log(operations, arguments) that processes a sequence of commands on an internal EntityLog object and returns one result per command.
Commands
"add_observation" — Log one observation.
Arguments: [system_id, entity_id, timestamp, metadata]
system_id(string): the name of the sensor system making the observation (e.g."CAMERA").entity_id(string): the local ID assigned by that system (e.g."C-1").timestamp(integer): when the observation occurred.metadata(string): free-form payload.
Returns None.
"link_systems" — Declare that two local IDs refer to the same physical entity.
Arguments: [id1, id2]
After this call, all observations ever recorded under id1 or id2 (and anything already merged with either) belong to one unified entity. The link is transitive: if A and B were linked previously, linking B with C also brings A and C together.
Returns None.
"get_history" — Retrieve the full observation log for the entity associated with a given ID.
Arguments: [any_id]
Returns a list of [timestamp, entity_id, metadata] triples covering every observation ever recorded for that entity (across all local IDs in its group), sorted by:
timestampascendingsystem_idascending (tie-break)entity_idascending (tie-break)metadatastring representation ascending (final tie-break)
If any_id has never been seen, return [].
Constraints
1 ≤ len(operations) ≤ 10 000- Each
operations[i]is one of"add_observation","link_systems","get_history". timestampis a non-negative integer.system_id,entity_id, andmetadataare non-empty strings.- The same
entity_idmay appear in multiple"add_observation"calls, possibly from differentsystem_idvalues. - Calling
"link_systems"on two IDs that are already part of the same entity has no effect. - Calling
"link_systems"with an ID that has no prior observations is valid; future"add_observation"calls for that ID will join the correct entity. len(operations) == len(arguments).
Examples
Example 1
Input: run_entity_log(['add_observation', 'add_observation', 'link_systems', 'get_history', 'get_history'], [['LIDAR', 'L-1', 100, 'loc:0,0'], ['RADAR', 'R-5', 105, 'loc:1,1'], ['L-1', 'R-5'], ['L-1'], ['R-5']])
Output: [None, None, None, [[100, 'L-1', 'loc:0,0'], [105, 'R-5', 'loc:1,1']], [[100, 'L-1', 'loc:0,0'], [105, 'R-5', 'loc:1,1']]]
Example 2
Input: run_entity_log(['add_observation', 'add_observation', 'link_systems', 'link_systems', 'add_observation', 'get_history'], [['CAMERA', 'C-1', 20, 'car'], ['RADAR', 'R-1', 10, 'vehicle'], ['C-1', 'R-1'], ['R-1', 'C-1'], ['LIDAR', 'C-1', 15, 'detected'], ['R-1']])
Output: [None, None, None, None, None, [[10, 'R-1', 'vehicle'], [15, 'C-1', 'detected'], [20, 'C-1', 'car']]]
Hints
Hint 1
Think about what data structure lets you group IDs together, merge groups efficiently, and look up which group any ID belongs to — without scanning all IDs every time.
Hint 2
Store the observation list at the group's representative (root), not at each individual ID. That way a link_systems call just combines two lists instead of scattering records across many places.
Hint 3
After a merge, the combined list needs to be in sorted order before the next get_history call. If each group's list is already sorted, two sorted lists can be merged in linear time rather than re-sorted from scratch — but sorting at read time also works if inserts are the bottleneck.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem has two independent subproblems that compose together.
1. Grouping IDs that refer to the same entity
Whenever "link_systems" is called, two potentially large groups of IDs must be united, and that union must be reflected in every future "get_history". This is exactly what a Disjoint Set Union (DSU) structure handles. Each ID has a parent pointer; following parents leads to a single canonical root for the group. Two techniques keep it efficient:
- Path compression — after finding the root, flatten all visited nodes to point directly at it, so future lookups are nearly O(1).
- Union by size — always attach the smaller group under the larger root, keeping tree height bounded.
2. Storing observations efficiently
Rather than keeping a list of observations on every individual ID, we store one list per root. When two groups are linked, their two lists are concatenated under the surviving root. A "get_history" call then sorts that single list and returns it.
Sorting at read time is correct because the reference solution doesn't require the list to be sorted between writes — only the value returned to the caller must be sorted. This keeps "add_observation" and "link_systems" cheap (no sorting work on write).
Tie-breaking determinism
Each entry is stored as (timestamp, system_id, entity_id, metadata). The sort key uses all four fields in that order, with str(metadata) as the final tie-break so that metadata values of any comparable type sort safely.
Why it is correct
- Completeness after link:
link_systemsmoves the smaller root's entire history list into the larger root's list. No record is dropped. - Transitivity: DSU path compression means that even after a chain of links (
A↔B,B↔C,C↔D), all four IDs resolve to the same root, and all their histories are consolidated in one list. - Idempotency: If both IDs already share a root,
link_systemsreturns immediately without changing anything. - Unknown IDs on fetch:
get_historychecksself.parentbefore doing anything and returns[]if the ID was never seen. - Late observations:
add_observationalways calls_find, which returns the current root at call time. If the ID was linked into a larger group earlier, the new record lands in the correct place automatically.
Complexity
| Operation | Time | Notes |
|---|---|---|
add_observation | O(α(I)) | α is the inverse-Ackermann factor from path compression, effectively constant |
link_systems | O(α(I) + a + b) | a and b are the sizes of the two history lists being concatenated |
get_history | O(α(I) + k log k) | k is the number of records in the group; Timsort dominates |
Space is O(N + I) where N is the total number of observations and I is the number of distinct IDs.
In practice, sensor data arrives roughly in time order, so the list handed to sort at read time is nearly sorted already, and Python's Timsort handles that in close to O(k).
from typing import List
class EntityLog:
def __init__(self):
self.parent = {} # id -> parent id
self.size = {} # root -> group size (number of IDs)
self.history = {} # root -> list of (timestamp, system_id, entity_id, metadata)
def _find(self, x):
# Initialise a new ID as its own singleton root on first contact.
if x not in self.parent:
self.parent[x] = x
self.size[x] = 1
self.history[x] = []
# Path-compressed find.
if self.parent[x] != x:
self.parent[x] = self._find(self.parent[x])
return self.parent[x]
def add_observation(self, system_id, entity_id, timestamp, metadata):
root = self._find(entity_id)
self.history[root].append((timestamp, system_id, entity_id, metadata))
def link_systems(self, id1, id2):
root1 = self._find(id1)
root2 = self._find(id2)
if root1 == root2:
return # already the same entity — nothing to do
# Union by size: attach the smaller group under the larger one.
if self.size[root1] < self.size[root2]:
root1, root2 = root2, root1
self.parent[root2] = root1
self.size[root1] += self.size[root2]
# Move root2's observations into root1's list.
self.history[root1].extend(self.history.pop(root2))
def get_history(self, any_id):
if any_id not in self.parent:
return []
root = self._find(any_id)
records = self.history[root]
# Sort by timestamp, then system_id, then entity_id, then str(metadata)
# as the final deterministic tie-break.
records.sort(key=lambda r: (r[0], r[1], r[2], str(r[3])))
return [[ts, eid, md] for ts, _sid, eid, md in records]
def run_entity_log(operations: List[str], arguments: List[List]) -> List:
log = EntityLog()
results = []
for op, args in zip(operations, arguments):
if op == "add_observation":
log.add_observation(*args)
results.append(None)
elif op == "link_systems":
log.link_systems(*args)
results.append(None)
elif op == "get_history":
results.append(log.get_history(*args))
else:
raise ValueError("Unknown operation: " + op)
return results