Unrolled Linked List Lookup and Insertion
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Design and simulate an unrolled linked list — a linear sequence maintained as a singly linked chain of fixed-bound array chunks (blocks) rather than one contiguous dynamic array. Every nonempty block holds up to capacity signed 32-bit integers in sequence order.
Starting from an empty sequence, implement unrolled_list(operations, capacity) to execute a batch of indexed commands and return a list containing one integer response per command:
[0, index, value]: placevalueright ahead of the element currently at 0-basedindex(whenindexequals the current sequence length, appendvalueat the tail), and record the updated sequence length.[1, index]: read and record the element currently located at 0-basedindex.
Your block chain must preserve these structural rules after every command:
- Blocks appear in left-to-right sequence order, and every nonempty block stores between
1andcapacityelements. - Every block other than the final tail block contains at least
floor(capacity / 2)elements. (Element removal is never requested.) - Whenever an insertion targets a block that already holds
capacityelements, divide the resultingcapacity + 1ordered elements across two adjacent blocks so relative order, thecapacityupper limit, and thefloor(capacity / 2)minimum occupancy all hold. Any split point satisfying those bounds is valid.
Examples
Example 1
Input:
capacity = 3
operations = [[0, 0, 40], [0, 1, 80], [0, 1, 60], [0, 0, 20], [1, 2], [0, 2, 50], [1, 4]]
Output: [1, 2, 3, 4, 60, 5, 80]
Walk-through of the sequence state:
- [0, 0, 40] inserts 40 -> [40] (length 1).
- [0, 1, 80] appends 80 -> [40, 80] (length 2).
- [0, 1, 60] inserts 60 before 80 -> [40, 60, 80], filling the block to capacity 3 (length 3).
- [0, 0, 20] inserts 20 at index 0 into the full block, splitting [20, 40, 60, 80] into [20, 40] -> [60, 80] (length 4).
- [1, 2] reads global index 2, returning 60.
- [0, 2, 50] inserts 50 before 60 -> [20, 40, 50] -> [60, 80] (length 5).
- [1, 4] reads global index 4, returning 80.
Example 2
Input:
capacity = 2
operations = [[0, 0, 15], [0, 0, -4], [0, 1, 12], [1, 0], [1, 1], [1, 2]]
Output: [1, 2, 3, -4, 12, 15]
The first two insertions build [-4, 15] (lengths 1 and 2). Inserting 12 at index 1 overflows capacity 2 and splits [-4, 12, 15] into [-4] -> [12, 15] (length 3, with 1 >= floor(2 / 2) in the leading block). Reading indices 0, 1, and 2 then returns -4, 12, and 15.
Constraints
2 <= capacity <= 640 <= len(operations) <= 20,000- Inserted values fit in signed 32-bit integers (
-2^31 <= value <= 2^31 - 1). - Every index is guaranteed valid for the current length
size:0 <= index <= sizefor[0, index, value]and0 <= index < sizefor[1, index]. - Must use a genuine linked-block structure rather than a single flat array.
Step-by-step walkthrough
Understand what an unrolled linked list is
A flat array lets you jump to index
iinO(1)time, but inserting near the front shifts up tonelements. A standard singly linked list splices in a node locally without shifting, but reaching indexifollowsiseparate pointers one element at a time.An unrolled linked list gets the best of both worlds by chaining together small arrays called blocks, each holding up to
capacityintegers in sequence order:Global sequence: [ 20, 40, 60, 80 ] (capacity = 3, size = 4) Global indices: 0 1 2 3 head ---> +-----------+ +-----------+ | [20, 40 ] | ---> | [60, 80 ] | ---> None +-----------+ +-----------+ offsets 0, 1 offsets 0, 1We process a list of commands starting from an empty chain (
2 <= capacity <= 64, up to20,000commands):[0, index, value]: placevalueimmediately before the element currently atindex(index == sizeappends at the tail), and return the updated sequence length.[1, index]: return the integer currently stored atindex.
Besides returning the right numbers, our blocks must maintain two structural invariants:
- Capacity cap: every nonempty block holds at most
capacityvalues. - Half-full occupancy: every block except the final block holds at least
floor(capacity / 2)values.
Map a global index to a `(block, offset)` pair
To find global
index, start atheadand compareindexagainstlen(block.values). Wheneverindexlies past the current block, subtractlen(block.values)fromindexand advanceblock = block.next—skipping an entire chunk of elements in a single pointer hop.Look carefully at what happens right on a block boundary, such as
index = 2on[20, 40] -> [60, 80]:head: [ 20, 40 ] (len = 2) ---> next: [ 60, 80 ] (len = 2) idx 0, 1 idx 2, 3 - get(2): valid offsets in head are 0 and 1. Since 2 >= 2, we MUST advance to `next` with index = 2 - 2 = 0, reading next.values[0] == 60. --> loop condition: `index >= len` - insert(2, 50): placing 50 at offset 2 (the end) of head produces [20, 40, 50] -> [60, 80], which STILL puts 50 immediately before 60! Even better, on append (`index == size = 4`), stopping when `index == len` lands cleanly at offset 2 of the tail block instead of walking off `tail.next` into `None`! --> loop condition: `index > len`That single character difference—
index >= len(block.values)ingetversusindex > len(block.values)ininsert—handles both block boundaries and end-of-list appends with zero extra special cases.Prove why splitting a full block in half maintains every invariant
What happens when
insertlands on a block that already holdscapacityvalues? Inserting one more producescapacity + 1ordered values. We split thosecapacity + 1values atmid = (capacity + 1) // 2:- Left block keeps the first
mid = floor((capacity + 1) / 2)values. - Right block receives the remaining
(capacity + 1) - mid = ceil((capacity + 1) / 2)values.
Let's check both even and odd capacities (
capacity >= 2):- Even
capacity = 2m(m >= 1):2m + 1splits intomandm + 1. Sincefloor(capacity / 2) = mandm + 1 <= 2m, both blocks lie inside[floor(capacity / 2), capacity]. - Odd
capacity = 2m + 1(m >= 1):2m + 2splits intom + 1andm + 1. Sincefloor(capacity / 2) = mandm + 1 <= 2m + 1, both blocks again lie inside[floor(capacity / 2), capacity].
What about the very first block when it starts with just
1element (which is belowfloor(capacity / 2)whencapacity >= 4)? Until that block fills all the way up tocapacityand splits,head.nextisNone—so it is the final block, which the occupancy rule explicitly exempts! And because there is nodeleteoperation, blocks never shrink once created.- Left block keeps the first
Code `Block` and `get`
Each
Blockstoresself.values(a small Python list) andself.next.UnrolledLinkedListtrackscapacity,head, and totalsize:from typing import List class Block: """One node in the unrolled linked list storing up to `capacity` elements in order.""" def __init__(self, values: List[int]) -> None: # values: Python list of 1..capacity ints in sequence order, e.g. [20, 40] self.values = values # next: reference to the following Block in sequence order, or None at the tail self.next = None class UnrolledLinkedList: """Linked chain of small arrays (Blocks), balancing fast block hops with small local shifts.""" def __init__(self, capacity: int) -> None: self.capacity = capacity # head: first Block in the chain (None when size == 0) self.head = None self.size = 0 def get(self, index: int) -> int: # Phase 1 (get): Skip whole blocks until `index` falls strictly inside `block.values`. # Use `>=` because valid offsets in `block.values` are 0 .. len(block.values) - 1; # when `index == len(block.values)`, the target element is offset 0 of `block.next`. block = self.head while index >= len(block.values): index -= len(block.values) block = block.next return block.values[index]Code `insert`, `_split_and_insert`, and the dispatcher
When splitting a full
block, build the temporarycombinedlist ofcapacity + 1items before slicing atmid; that way you never have to compute whetheroffsetfalls in the left half or right half. Then splicenew_blockright afterblockin the proper pointer order:Before split: block (full) -------------------------> old_next Step 1: new_block = Block(combined[mid:]) new_block.next = block.next (points new_block -> old_next FIRST!) Step 2: block.values = combined[:mid] block.next = new_block (now safe to point block -> new_block) After split: block (left half) ---> new_block (right half) ---> old_nextdef insert(self, index: int, value: int) -> int: # Special case: first insertion into an empty list creates the head (and final) block. if self.head is None: self.head = Block([value]) self.size = 1 return self.size # Phase 1 (insert): Walk to the target block and local offset. # Crucial boundary (`>` instead of `>=`): when `index == len(block.values)`, we STOP on # the current block and place `value` at its end. That sits right before offset 0 of # `block.next`, and when `index == self.size` (append), it stops at the tail block # instead of walking off `block.next` into None. block = self.head while index > len(block.values): index -= len(block.values) block = block.next # Phase 2 (insert): Insert in place if room remains; otherwise split the full block in two. if len(block.values) < self.capacity: block.values.insert(index, value) else: self._split_and_insert(block, index, value) self.size += 1 return self.size def _split_and_insert(self, block: Block, offset: int, value: int) -> None: """Insert `value` into a full block of `capacity` items, then split `capacity + 1` in half.""" # Build the ordered `capacity + 1` items first so we do not have to compute whether # `offset` belongs in the left half or right half after splitting. combined = block.values[:offset] + [value] + block.values[offset:] mid = len(combined) // 2 # floor((capacity + 1) / 2), always >= floor(capacity / 2) # Save `block.next` into `new_block.next` BEFORE overwriting `block.next` so we never # lose the rest of the linked chain. new_block = Block(combined[mid:]) new_block.next = block.next block.values = combined[:mid] block.next = new_blockFinally,
unrolled_listloops throughoperationsand collects one integer result per operation.Trace Example 1 and Example 2 step by step
Example 1 (capacity = 3): [0, 0, 40] -> empty list: create head [40] -> returns 1 [0, 1, 80] -> 1 is not > len([40])=1: insert at offset 1 -> [40, 80] -> returns 2 [0, 1, 60] -> 1 is not > 2: insert at offset 1 -> [40, 60, 80] -> returns 3 [0, 0, 20] -> head is full (3==3): combined=[20, 40, 60, 80], mid=2 splits into [20, 40] -> [60, 80] -> returns 4 [1, 2] -> 2 >= len([20, 40])=2: index = 2 - 2 = 0 on [60, 80] -> 60 -> returns 60 [0, 2, 50] -> 2 is not > len([20, 40])=2: append to head -> [20, 40, 50] -> returns 5 [1, 4] -> 4 >= len([20, 40, 50])=3: index = 4 - 3 = 1 on [60, 80] -> 80 -> returns 80 Output: [1, 2, 3, 4, 60, 5, 80] Example 2 (capacity = 2): [0, 0, 15] -> [15] -> returns 1 [0, 0, -4] -> [-4, 15] -> returns 2 [0, 1, 12] -> full (2==2): combined=[-4, 12, 15], mid=1 -> [-4] -> [12, 15] -> returns 3 [1, 0], [1, 1], [1, 2] -> reads -4, then 12, then 15 -> -4, 12, 15 Output: [1, 2, 3, -4, 12, 15]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple class Block: """One node in the unrolled linked list storing up to `capacity` elements in order.""" def __init__(self, values: List[int]) -> None: # values: Python list of 1..capacity ints in sequence order, e.g. [20, 40] self.values = values # next: reference to the following Block in sequence order, or None at the tail self.next = None class UnrolledLinkedList: """Linked chain of small arrays (Blocks), balancing fast block hops with small local shifts.""" def __init__(self, capacity: int) -> None: self.capacity = capacity # head: first Block in the chain (None when size == 0) self.head = None self.size = 0 def get(self, index: int) -> int: # Phase 1 (get): Skip whole blocks until `index` falls strictly inside `block.values`. # Use `>=` because valid offsets in `block.values` are 0 .. len(block.values) - 1; # when `index == len(block.values)`, the target element is offset 0 of `block.next`. block = self.head while index >= len(block.values): index -= len(block.values) block = block.next return block.values[index] def insert(self, index: int, value: int) -> int: # Special case: first insertion into an empty list creates the head (and final) block. if self.head is None: self.head = Block([value]) self.size = 1 return self.size # Phase 1 (insert): Walk to the target block and local offset. # Crucial boundary (`>` instead of `>=`): when `index == len(block.values)`, we STOP on # the current block and place `value` at its end. That sits right before offset 0 of # `block.next`, and when `index == self.size` (append), it stops at the tail block # instead of walking off `block.next` into None. block = self.head while index > len(block.values): index -= len(block.values) block = block.next # Phase 2 (insert): Insert in place if room remains; otherwise split the full block in two. if len(block.values) < self.capacity: block.values.insert(index, value) else: self._split_and_insert(block, index, value) self.size += 1 return self.size def _split_and_insert(self, block: Block, offset: int, value: int) -> None: """Insert `value` into a full block of `capacity` items, then split `capacity + 1` in half.""" # Build the ordered `capacity + 1` items first so we do not have to compute whether # `offset` belongs in the left half or right half after splitting. combined = block.values[:offset] + [value] + block.values[offset:] mid = len(combined) // 2 # floor((capacity + 1) / 2), always >= floor(capacity / 2) # Save `block.next` into `new_block.next` BEFORE overwriting `block.next` so we never # lose the rest of the linked chain. new_block = Block(combined[mid:]) new_block.next = block.next block.values = combined[:mid] block.next = new_block def unrolled_list(operations: List[List[int]], capacity: int) -> List[int]: # Dispatch each operation: [0, index, value] -> insert (returns new size), [1, index] -> get. sequence = UnrolledLinkedList(capacity) results: List[int] = [] for operation in operations: op_type = operation[0] if op_type == 0: new_size = sequence.insert(operation[1], operation[2]) results.append(new_size) elif op_type == 1: element = sequence.get(operation[1]) results.append(element) else: raise ValueError(f"Unknown operation code: {op_type}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Think of seating passengers on a train made of small carriages (capacity seats per carriage) rather than on one giant park bench or a chain of single-seat unicycles. An unrolled linked list (a linked list where every node stores a small array of up to capacity elements instead of just one element) works just like that train: to reach passenger index, you walk past whole carriages at a time by subtracting each carriage's headcount, and when a new passenger squeezes in, only the few people inside that one carriage scoot over—or, if that carriage is full, its capacity + 1 riders split cleanly across two half-full carriages linked side by side.
Why do the two basic structures fall short? Storing everything in one flat resizable array violates the problem's structural requirement and forces up to n elements to shift in memory whenever someone inserts near index 0. Conversely, a standard singly linked list with one integer per node avoids shifting but must chase i separate memory pointers to reach index i, wasting both pointer memory and CPU cache speed.
Trace Example 2 (capacity = 2) to watch the blocks grow and split:
insert(0, 15): list is empty, so create the head block[15](returns size1).insert(0, -4): head has1 < 2items, so insert at offset0to get[-4, 15](returns size2).insert(1, 12): head is full (2 == 2), so buildcombined = [-4, 12, 15]and split at3 // 2 = 1into[-4] -> [12, 15](returns size3; the non-final block has1 >= floor(2 / 2)item).get(0),get(1),get(2): index0reads-4from[-4]; indices1and2subtractlen([-4]) = 1and read offsets0(12) and1(15) from[12, 15].
Complexity
Let n be the current sequence length, c be capacity, and B be the number of blocks. Because every block except the last holds at least floor(c / 2) elements, B <= n / floor(c / 2) + 1, which scales as O(n / c + 1).
- Time per
get:O(n / c + 1), because we hop across at mostBblocks subtracting their lengths and then perform anO(1)list index inside the target block. - Time per
insert:O(n / c + c), because walking to the target block visits at mostBblocks, and inserting inside the block (or copyingc + 1elements into two halves during a split) touches at mostc + 1values. Acrossmtotal operations (n <= m), total time isO(m * (m / c + c)). - Space:
O(n), because each of theninserted integers is stored once inside exactly one nonemptyBlock, so at mostnblock objects exist.
Edge cases
- Empty list on first insert:
self.headisNone, so we createBlock([value])directly; even ifcapacity >= 4, this 1-element block is the final block and satisfies the occupancy exemption. - Appending at the end (
index == size):insert'swhile index > len(block.values)loop stops at the tail block withindex == len(tail.values)instead of advancing intoNone. - Inserting on a block boundary: when
indexequals the cumulative size of the firstkblocks,insertappends to blockk, which sits immediately before offset0of blockk + 1and preserves exact sequence order. - Minimum capacity (
capacity = 2): a full block plus one new value has3items and splits into sizes1and2, both satisfying>= floor(2 / 2) = 1and<= 2. - Empty
operationslist: the loop does zero iterations and returns[]. - 32-bit extremes and duplicate values: Python integers have arbitrary precision, and duplicates do not affect index arithmetic.
Common mistakes
- Using
>=ininsert's block walk:getneedsindex >= len(block.values)because offsetlenis out of bounds for reading, whereasinsertneeds strictindex > len(block.values)soindex == sizeappends to the tail block instead of crashing onNone.values. - Overwriting
block.nextbefore linkingnew_block.next: settingblock.next = new_blockfirst orphans every block afterblock; always setnew_block.next = block.nextfirst. - Splitting before inserting at the old offset: if you split a full block first, an
offsetin the second half is no longer valid onblock; forming thec + 1-elementcombinedlist first eliminates offset-remapping bugs. - Placing a middle insertion into a brand-new 1-element block: when
capacity >= 4, a 1-element block in the middle of the chain violates the>= floor(capacity / 2)rule for non-final blocks. - Returning
0or the old size frominsert: operation0must incrementself.sizeand return the new size.
Alternative approaches
- Tail pointer + append-tail split: keeping a
self.tailpointer and splitting an end-append(capacity + 1)into[capacity items] -> [1 new item]makes pure appendsO(1)and keeps earlier blocks 100% full instead of 50% full (this is another reason the specification exempts the final block from thefloor(c / 2)lower bound). Middle inserts still walk fromheadand split in half. - Tree of blocks (rope / B-tree): organizing the blocks as the leaves of a B-tree (a self-balancing multi-way tree where internal nodes store subtree element counts) or a rope (a binary tree over small array chunks weighted by subtree length) reduces the block-finding walk from
O(n / c)toO(log(n / c))at the cost of maintaining parent/subtree counts on splits.
Follow-up questions
- How would you support indexed deletion while maintaining the half-capacity minimum on non-tail blocks? Walk to the target block (tracking
prev_block) and pop the value at the local offset. If the block is the tail and becomes empty, unlink it viaprev_block.next = None(orself.head = None). Otherwise, ifblockis non-final and drops tofloor(c / 2) - 1items, inspectblock.next: ifblock.nexthas strictly more thanfloor(c / 2)items, borrow its first item (block.values.append(block.next.values.pop(0))); otherwise mergeblock.nextintoblock(giving at most(floor(c / 2) - 1) + floor(c / 2) <= c - 1items) and bypassblock.next, keepingdeleteinO(n / c + c)time. - What trade-offs guide the choice of block capacity in real hardware environments? Mathematically, per-operation work
O(n / c + c)balances block hops against in-block shifts whenn / c ≈ c, givingc ≈ sqrt(n)andO(sqrt(n))time per operation. On real hardware, engineers also size each block to span a few CPU cache lines (the fixed-size 64-byte chunks of memory the processor fetches from RAM in a single burst), such as16to64integers, because scanning contiguous memory inside a cache line is vastly faster than chasing pointers across scattered heap allocations. - How can block lookup be accelerated from linear in the block count to logarithmic? Maintaining a flat side array of block pointers with prefix sizes lets you binary-search for the block in
O(log B), but anyinsertmust still increment every later prefix count inO(B). To make bothgetandinsertlogarithmic inB, store subtree element counts in a balanced tree over the blocks (a rope or Fenwick-like hierarchy over block sizes), bringing each operation down toO(log B + c).
Follow-up questions
- How would you support indexed deletion while maintaining the half-capacity minimum on non-tail blocks?
- What trade-offs guide the choice of block capacity in real hardware environments?
- How can block lookup be accelerated from linear in the block count to logarithmic?
Similar questions
- Memory Layout Trade-Offs: Arrays vs. Linked Lists
- Vectorized MSE and Linear Regression
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance