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]: place value right ahead of the element currently at 0-based index (when index equals the current sequence length, append value at the tail), and record the updated sequence length.
  • [1, index]: read and record the element currently located at 0-based index.

Your block chain must preserve these structural rules after every command:

  1. Blocks appear in left-to-right sequence order, and every nonempty block stores between 1 and capacity elements.
  2. Every block other than the final tail block contains at least floor(capacity / 2) elements. (Element removal is never requested.)
  3. Whenever an insertion targets a block that already holds capacity elements, divide the resulting capacity + 1 ordered elements across two adjacent blocks so relative order, the capacity upper limit, and the floor(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 <= 64
  • 0 <= 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 <= size for [0, index, value] and 0 <= index < size for [1, index].
  • Must use a genuine linked-block structure rather than a single flat array.

Step-by-step walkthrough

  1. Understand what an unrolled linked list is

    A flat array lets you jump to index i in O(1) time, but inserting near the front shifts up to n elements. A standard singly linked list splices in a node locally without shifting, but reaching index i follows i separate 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 capacity integers 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, 1
    

    We process a list of commands starting from an empty chain (2 <= capacity <= 64, up to 20,000 commands):

    • [0, index, value]: place value immediately before the element currently at index (index == size appends at the tail), and return the updated sequence length.
    • [1, index]: return the integer currently stored at index.

    Besides returning the right numbers, our blocks must maintain two structural invariants:

    1. Capacity cap: every nonempty block holds at most capacity values.
    2. Half-full occupancy: every block except the final block holds at least floor(capacity / 2) values.
  2. Map a global index to a `(block, offset)` pair

    To find global index, start at head and compare index against len(block.values). Whenever index lies past the current block, subtract len(block.values) from index and advance block = 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 = 2 on [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) in get versus index > len(block.values) in insert—handles both block boundaries and end-of-list appends with zero extra special cases.

  3. Prove why splitting a full block in half maintains every invariant

    What happens when insert lands on a block that already holds capacity values? Inserting one more produces capacity + 1 ordered values. We split those capacity + 1 values at mid = (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 + 1 splits into m and m + 1. Since floor(capacity / 2) = m and m + 1 <= 2m, both blocks lie inside [floor(capacity / 2), capacity].
    • Odd capacity = 2m + 1 (m >= 1): 2m + 2 splits into m + 1 and m + 1. Since floor(capacity / 2) = m and m + 1 <= 2m + 1, both blocks again lie inside [floor(capacity / 2), capacity].

    What about the very first block when it starts with just 1 element (which is below floor(capacity / 2) when capacity >= 4)? Until that block fills all the way up to capacity and splits, head.next is None—so it is the final block, which the occupancy rule explicitly exempts! And because there is no delete operation, blocks never shrink once created.

  4. Code `Block` and `get`

    Each Block stores self.values (a small Python list) and self.next. UnrolledLinkedList tracks capacity, head, and total size:

    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]
    
  5. Code `insert`, `_split_and_insert`, and the dispatcher

    When splitting a full block, build the temporary combined list of capacity + 1 items before slicing at mid; that way you never have to compute whether offset falls in the left half or right half. Then splice new_block right after block in 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_next
    
        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
    

    Finally, unrolled_list loops through operations and collects one integer result per operation.

  6. 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]
    
  7. 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 size 1).
  • insert(0, -4): head has 1 < 2 items, so insert at offset 0 to get [-4, 15] (returns size 2).
  • insert(1, 12): head is full (2 == 2), so build combined = [-4, 12, 15] and split at 3 // 2 = 1 into [-4] -> [12, 15] (returns size 3; the non-final block has 1 >= floor(2 / 2) item).
  • get(0), get(1), get(2): index 0 reads -4 from [-4]; indices 1 and 2 subtract len([-4]) = 1 and read offsets 0 (12) and 1 (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 most B blocks subtracting their lengths and then perform an O(1) list index inside the target block.
  • Time per insert: O(n / c + c), because walking to the target block visits at most B blocks, and inserting inside the block (or copying c + 1 elements into two halves during a split) touches at most c + 1 values. Across m total operations (n <= m), total time is O(m * (m / c + c)).
  • Space: O(n), because each of the n inserted integers is stored once inside exactly one nonempty Block, so at most n block objects exist.

Edge cases

  • Empty list on first insert: self.head is None, so we create Block([value]) directly; even if capacity >= 4, this 1-element block is the final block and satisfies the occupancy exemption.
  • Appending at the end (index == size): insert's while index > len(block.values) loop stops at the tail block with index == len(tail.values) instead of advancing into None.
  • Inserting on a block boundary: when index equals the cumulative size of the first k blocks, insert appends to block k, which sits immediately before offset 0 of block k + 1 and preserves exact sequence order.
  • Minimum capacity (capacity = 2): a full block plus one new value has 3 items and splits into sizes 1 and 2, both satisfying >= floor(2 / 2) = 1 and <= 2.
  • Empty operations list: 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 >= in insert's block walk: get needs index >= len(block.values) because offset len is out of bounds for reading, whereas insert needs strict index > len(block.values) so index == size appends to the tail block instead of crashing on None.values.
  • Overwriting block.next before linking new_block.next: setting block.next = new_block first orphans every block after block; always set new_block.next = block.next first.
  • Splitting before inserting at the old offset: if you split a full block first, an offset in the second half is no longer valid on block; forming the c + 1-element combined list 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 0 or the old size from insert: operation 0 must increment self.size and return the new size.

Alternative approaches

  • Tail pointer + append-tail split: keeping a self.tail pointer and splitting an end-append (capacity + 1) into [capacity items] -> [1 new item] makes pure appends O(1) and keeps earlier blocks 100% full instead of 50% full (this is another reason the specification exempts the final block from the floor(c / 2) lower bound). Middle inserts still walk from head and 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) to O(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 via prev_block.next = None (or self.head = None). Otherwise, if block is non-final and drops to floor(c / 2) - 1 items, inspect block.next: if block.next has strictly more than floor(c / 2) items, borrow its first item (block.values.append(block.next.values.pop(0))); otherwise merge block.next into block (giving at most (floor(c / 2) - 1) + floor(c / 2) <= c - 1 items) and bypass block.next, keeping delete in O(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 when n / c ≈ c, giving c ≈ sqrt(n) and O(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 as 16 to 64 integers, 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 any insert must still increment every later prefix count in O(B). To make both get and insert logarithmic in B, store subtree element counts in a balanced tree over the blocks (a rope or Fenwick-like hierarchy over block sizes), bringing each operation down to O(log B + c).

Follow-up questions

Similar questions

More Indeed interview questions

All 3 Indeed questions →