Practice/xAI/Radix Cache
CodingMust
Design and implement a Prefix Radix Cache that efficiently stores sequences of numbers using a radix tree (also known as a prefix tree or compressed trie). Unlike a standard trie where each node represents a single element, a radix tree compresses chains of single-child nodes into single edges containing multiple elements.
This data structure is commonly used in:
Implement a RadixCache class that can insert sequences and build a proper radix tree structure.
` tree = RadixCache() tree.insert([10, 20]) tree.insert([1, 2, 3]) tree.insert([1, 2, 3, 4, 5, 6])
`
Notice how:
[1, 2, 3] and [1, 2, 3, 4, 5, 6] share the prefix [1, 2, 3][10, 20] is a separate branch (no common prefix with [1, ...])Handle the case where inserting a new sequence requires splitting an existing edge. This happens when a new sequence shares only a partial prefix with an existing edge.
` tree = RadixCache() tree.insert([1, 2, 3]) tree.insert([1, 2, 3, 4, 5, 6]) tree.insert([1, 2, 3, 40, 50, 60, 70, 80]) tree.insert([1, 2, 3, 40, 50, 60, 700, 800])
`
When inserting [1, 2, 3, 40, 50, 60, 700, 800] and edge [40, 50, 60, 70, 80] already exists:
Find the common prefix: [40, 50, 60]
Split the existing edge into:
[40, 50, 60][70, 80]Add new child edge for the new sequence's remainder: [700, 800]
Extend your implementation with search, prefix matching, and sequence retrieval operations.
` tree = RadixCache() tree.insert([1, 2, 3]) tree.insert([1, 2, 3, 4, 5]) tree.insert([10, 20])
tree.search([1, 2, 3]) # True (complete sequence) tree.search([1, 2]) # False (prefix exists but not complete) tree.search([10, 20]) # True
tree.prefix_match([1, 2, 3, 4, 5, 6, 7]) # Returns [1, 2, 3, 4, 5] tree.prefix_match([1, 2]) # Returns [] (not a complete sequence)
tree.get_all_sequences() # Returns [[1, 2, 3], [1, 2, 3, 4, 5], [10, 20]] `
search(sequence): Check if exact sequence exists (must be a terminal node)prefix_match(sequence): Find longest prefix that is a complete sequenceget_all_sequences(): Return all complete sequences via DFS traversal