Prefix-Compressed Trie for Integer Sequences
Data Structure DesignAuto-graded · 16 test casesLast updated
Simulate operations on a prefix-compressed radix tree storing integer sequences, supporting sequence insertions and depth-first tree serialization.
Design and process a sequence of operations on a compact prefix tree (radix tree) designed to store non-empty sequences of non-negative integers.
Each edge in the radix tree is associated with a non-empty list of integers. The tree maintains two structural rules at all times:
- Unique Branching: No two outgoing edges from the same node start with the same integer.
- Maximal Compression: Edges extend as far as possible without splitting, diverging only where sequences split or where an inserted sequence ends.
You are given two lists representing a sequence of operations:
operations: A list of strings, where each element is either"insert"or"dump".arguments: A list of argument lists corresponding to each operation:- For
"insert",arguments[i]is a list containing a single integer sequence, e.g.,[[1, 2, 3]]. - For
"dump",arguments[i]is empty, i.e.,[].
- For
Behavior of Operations
-
insert: Inserts an integer sequence into the radix tree.- Traversal begins at the root. At the current node, look for an existing child edge whose label begins with the next remaining integer of the insertion sequence.
- No matching child: Attach a new child node with an edge label equal to all remaining integers, then complete the operation.
- Full label match: If the sequence matches the child's edge label completely, advance down to that child node and continue with the remaining suffix of the sequence. If the sequence ends exactly at that child node, the operation completes without modifying the tree.
- Partial label match: If the sequence matches only a non-empty proper prefix of the child's edge label (or if the inserted sequence ends inside the label), split the edge:
- Replace the existing child edge with a new intermediate node labeled with the shared prefix.
- Attach the original child (holding its existing subtree intact) to the intermediate node with an edge labeled by the remaining suffix of its original edge label.
- If the inserted sequence has additional integers beyond the common prefix, attach a second new child to the intermediate node containing those remaining integers.
- Re-inserting an already present sequence or inserting a sequence that is a prefix/extension of an existing sequence must maintain the structural invariants.
- Returns
None(null).
-
dump: Returns a snapshot of the tree structure formatted as a list of strings.- Performs a depth-first traversal starting from the root (the root node itself is unlabeled and is not included in the output).
- Each visited non-root node generates one string: its edge label formatted as standard Python list string output (e.g.,
"[1, 2, 3]"), prepended by 2 space characters (" ") for each level of depth below the root (depth 0 for direct children of the root). - At every node, traverse children in ascending order of the first integer of their edge labels.
- Returns a list of formatted strings.
Return a list containing the result of each operation in the order provided.
Constraints
- $1 \le \text{len(operations)} \le 10^4$
- $1 \le \text{length of each inserted sequence} \le 10^3$
- $0 \le \text{each integer} \le 10^9$
- Total integers across all inserted sequences $\le 10^5$.
Examples
Example 1
Input: radix_cache(['insert', 'insert', 'insert', 'dump'], [[[10, 20]], [[1, 2, 3]], [[1, 2, 3, 4, 5, 6]], []])
Output: [None, None, None, ['[1, 2, 3]', ' [4, 5, 6]', '[10, 20]']]
Example 2
Input: radix_cache(['insert', 'insert', 'insert', 'insert', 'insert', 'dump'], [[[10, 20]], [[1, 2, 3]], [[1, 2, 3, 4, 5, 6]], [[1, 2, 3, 40, 50, 60, 70, 80]], [[1, 2, 3, 40, 50, 60, 700, 800]], []])
Output: [None, None, None, None, None, ['[1, 2, 3]', ' [4, 5, 6]', ' [40, 50, 60]', ' [70, 80]', ' [700, 800]', '[10, 20]']]
Hints
Hint 1
Use a node representation where children are indexed by the first integer of their edge label to achieve O(1) branching lookup.
Hint 2
When splitting an edge, make sure to preserve the entire subtree attached to the original node under the new split suffix label.
Hint 3
When dumping the structure, sort the children by their initial element before performing depth-first search, and maintain an explicit recursion/stack depth for indentation.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks us to maintain a radix tree (prefix-compressed trie) of integer sequences and produce formatted snapshots via DFS.
1. Data Structure Representation
Since no two outgoing edges from a node start with the same integer, we can store a node's children in a hash map (children) keyed by the first integer of the child edge label (child.label[0]). This allows $O(1)$ edge selection during traversal.
2. Insertion Logic
To insert a sequence seq:
- Start at
rootwithpos = 0. - Look up
node.children.get(seq[pos]).- If missing: Attach
Node(seq[pos:])as a child and terminate. - If present: Compare the existing
child.labelwithseq[pos:]to count matching elementscommon.- Full match (
common == len(label)): Advancepos += common, movenode = child, and repeat. - Partial match (
common < len(label)): Split the edge into an intermediate node (middle) holdinglabel[:common]. Place the old child (with its remaining suffixlabel[common:]and its subtree) undermiddle. If any unconsumed suffix ofseqremains (pos + common < len(seq)), attach a new child holdingseq[pos+common:]tomiddle. Replacechildwithmiddleundernode.children[seq[pos]].
- Full match (
- If missing: Attach
3. Dump Logic
To serialize the structure:
- Conduct a depth-first traversal starting from the children of the root.
- At each node, sort its children by the first element of their label (
label[0]) in ascending order. - Track node depth to prepend
2 * depthspace characters beforestr(node.label).
Complexity Analysis
- Time Complexity:
insert: $O(L)$ per insertion, where $L$ is the length of the inserted sequence, since we compare each element at most once and perform $O(1)$ dictionary lookups.dump: $O(N \log B + S)$, where $N$ is the total number of nodes, $B$ is the maximum branching factor at any node, and $S$ is the total length of label output strings.
- Space Complexity: $O(T)$ overall, where $T$ is the total number of integers stored across all insertions.
from typing import List, Optional
class Node:
def __init__(self, label: List[int]):
self.label = label
self.children = {}
def radix_cache(operations: List[str], arguments: List[List[List[int]]]) -> List[Optional[List[str]]]:
root = Node([])
results: List[Optional[List[str]]] = []
for operation, args in zip(operations, arguments):
if operation == "insert":
seq = args[0]
node = root
pos = 0
while pos < len(seq):
child = node.children.get(seq[pos])
if child is None:
node.children[seq[pos]] = Node(seq[pos:])
break
label = child.label
common = 0
limit = min(len(label), len(seq) - pos)
while common < limit and label[common] == seq[pos + common]:
common += 1
if common == len(label):
pos += common
node = child
continue
middle = Node(label[:common])
old_child = Node(label[common:])
old_child.children = child.children
middle.children[label[common]] = old_child
node.children[seq[pos]] = middle
child.children = {}
pos += common
if pos < len(seq):
middle.children[seq[pos]] = Node(seq[pos:])
break
results.append(None)
elif operation == "dump":
lines: List[str] = []
children = sorted(root.children.values(), key=lambda n: n.label[0])
stack = [(child, 0) for child in reversed(children)]
while stack:
node, depth = stack.pop()
lines.append(" " * depth + str(node.label))
children = sorted(node.children.values(), key=lambda n: n.label[0])
for child in reversed(children):
stack.append((child, depth + 1))
results.append(lines)
else:
raise ValueError("unsupported operation")
return results