Binary Layout Manager with Dynamic Field Insertion
Data Structure DesignAuto-graded · 13 test casesLast updated
Tests ability to maintain ordered sequences with efficient prefix-sum queries and positional insertions using balanced tree structures.
You are building a system to manage the memory layout of binary objects. Each object contains an ordered sequence of fields, where every field has a name and occupies a certain number of bytes. Fields are placed one after another with no gaps, starting at byte 0.
The byte offset of each field is determined by summing the sizes of all fields that come before it in the sequence.
Example layout:
Given fields (alpha, 4), (beta, 5), (gamma, 3) in that order:
| Field | Size | Byte Range |
|---|---|---|
| alpha | 4 | [0, 4) |
| beta | 5 | [4, 9) |
| gamma | 3 | [9, 12) |
Your task is to implement a function that processes a series of operations on a field layout:
getOffset(name): Return the starting byte offset of the field with the given name.insert(name, size, position): Insert a new field at the specified position in the field sequence (0-indexed). All fields currently at this position or later shift one position toward the end, and their byte offsets increase accordingly.
Input Format
fields: A list of[name, size]pairs representing the initial field sequence.operations: A list of operation names, each either"getOffset"or"insert".arguments: A list where each element contains the arguments for the corresponding operation:- For
"getOffset":[name] - For
"insert":[name, size, position]
- For
Output Format
Return a list of results, one per operation:
- For
"getOffset": the integer byte offset - For
"insert":None(ornull)
Example
Initial fields: [["foo", 3], ["bar", 6], ["baz", 2]]
Operations:
getOffset("bar")→3(foo occupies bytes 0-2)insert("qux", 2, 1)→ sequence becomes foo, qux, bar, bazgetOffset("bar")→5(foo: 0-2, qux: 3-4, bar starts at 5)getOffset("baz")→11(bar ends at 10)insert("end", 4, 4)→ appends to the endgetOffset("end")→13getOffset("foo")→0
Constraints
- 1 ≤ number of initial fields ≤ 10⁵
- 1 ≤ total operations ≤ 10⁵
- 1 ≤ field size ≤ 10⁴
- All field names are unique non-empty strings
getOffsetis only called on fields that exist- For
insertoperations: 0 ≤ position ≤ current field count - All byte offsets fit in a 64-bit signed integer
Examples
Example 1
Input: binary_layout_manager([['foo', 3], ['bar', 6], ['baz', 2]], ['getOffset', 'insert', 'getOffset', 'getOffset', 'insert', 'getOffset', 'getOffset'], [['bar'], ['qux', 2, 1], ['bar'], ['baz'], ['end', 4, 4], ['end'], ['foo']])
Output: [3, None, 5, 11, None, 13, 0]
Hints
Hint 1
Think about what getOffset really computes: it's a prefix sum over the field sequence. How can you maintain prefix sums when the sequence changes?
Hint 2
Inserting in the middle of a sequence is expensive with arrays. Consider a tree structure where in-order traversal gives the field order.
Hint 3
An implicit treap with subtree aggregates can support O(log n) insertion by position and O(log n) prefix-sum queries by walking up parent pointers.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires managing an ordered sequence of fields where we need to:
- Insert new fields at arbitrary positions in O(log n) time
- Compute byte offsets (prefix sums) in O(log n) time
The key insight is that a byte offset is simply the sum of all field sizes that appear earlier in the sequence. This is a prefix-sum query on a dynamic sequence.
Why simple approaches fail:
- Array with linear scan:
getOffsettakes O(n) time, too slow for 10⁵ operations - Precomputed offset array:
insertrequires updating all subsequent offsets in O(n) time - Fenwick tree: Positions aren't stable—inserting in the middle renumbers everything
Solution: Implicit Treap with Subtree Aggregates
We use a randomized binary search tree (treap) where nodes are ordered by their position in the sequence, not by any key value. Each node maintains:
size: bytes occupied by this fieldcount: number of nodes in its subtree (for position-based operations)total: sum of all sizes in its subtree (for offset computation)parent: pointer for upward traversalpriority: random value for balancing
Insert operation:
- Split the treap at the target position into two parts using the
countfield to navigate - Create the new node
- Merge: left part + new node + right part
getOffset operation:
- Start with the sum of the left subtree (fields before this one in its subtree)
- Walk up to the root via parent pointers
- When ascending from a right child: add the parent's size and its entire left subtree (they all come before us)
- When ascending from a left child: add nothing (parent comes after us)
Correctness
The treap maintains the in-order sequence of fields. Splitting by count at position k produces exactly the first k fields on the left. The upward walk accumulates precisely the bytes from all fields that precede the target in in-order traversal.
Complexity
- Time: O(log n) expected per operation due to treap's expected depth
- Space: O(n) for nodes and the name-to-node map
- Construction: O(n log n) expected for building the initial treap
Implementation
import random
from typing import List, Optional
class _LayoutNode:
__slots__ = ("name", "size", "priority", "left", "right", "parent", "count", "total")
def __init__(self, name, size, priority):
self.name = name
self.size = size
self.priority = priority
self.left = self.right = self.parent = None
self.count = 1
self.total = size
def _get_count(node):
return node.count if node else 0
def _get_total(node):
return node.total if node else 0
def _update_node(node):
node.count = 1 + _get_count(node.left) + _get_count(node.right)
node.total = node.size + _get_total(node.left) + _get_total(node.right)
if node.left:
node.left.parent = node
if node.right:
node.right.parent = node
def _merge_subtrees(left, right):
if not left:
if right:
right.parent = None
return right
if not right:
left.parent = None
return left
if left.priority < right.priority:
left.right = _merge_subtrees(left.right, right)
_update_node(left)
left.parent = None
return left
right.left = _merge_subtrees(left, right.left)
_update_node(right)
right.parent = None
return right
def _split_at_position(root, index):
if not root:
return None, None
if _get_count(root.left) >= index:
left, root.left = _split_at_position(root.left, index)
_update_node(root)
root.parent = None
if left:
left.parent = None
return left, root
root.right, right = _split_at_position(root.right, index - _get_count(root.left) - 1)
_update_node(root)
root.parent = None
if right:
right.parent = None
return root, right
def binary_layout_manager(fields, operations, arguments):
rng = random.Random(94721)
root = None
node_map = {}
for name, size in fields:
node = _LayoutNode(name, size, rng.randrange(1 << 60))
node_map[name] = node
root = _merge_subtrees(root, node)
results = []
for operation, args in zip(operations, arguments):
if operation == "getOffset":
node = node_map[args[0]]
offset = _get_total(node.left)
current = node
while current.parent:
parent = current.parent
if current is parent.right:
offset += parent.size + _get_total(parent.left)
current = parent
results.append(offset)
else:
name, size, position = args
node = _LayoutNode(name, size, rng.randrange(1 << 60))
left_part, right_part = _split_at_position(root, position)
root = _merge_subtrees(_merge_subtrees(left_part, node), right_part)
node_map[name] = node
results.append(None)
return results