KatInterview

Sequence Storage Trade-offs: Contiguous Arrays vs Pointer Chains

Linked ListsModel answer
MediumModel answerLinked Listsarrayslinked-listsunrolled-linked-list

Last updated

Contrast contiguous arrays, linked lists, and unrolled lists for indexed reads, inserts, growth, traversal speed, and cache behavior, and say when each one wins.

You are choosing a storage layout for an ordered sequence of elements. Discuss the following three candidates and how their memory layouts affect real performance:

  1. A fixed-size array.
  2. A resizable contiguous array (a dynamic array or vector).
  3. A singly or doubly linked list, and its variant where each node stores several consecutive elements (an unrolled linked list).

Your answer should cover:

  • Reading the element at index i.
  • Inserting an element, both when you already hold a node or iterator at the target position and when you only have an index.
  • Appending, including what happens when capacity runs out.
  • Full traversal, and why asymptotically equal traversals can differ greatly in wall-clock time.
  • Memory overhead per element.
  • Why storing several values per linked node is attractive, and what it does and does not improve.

State clearly what each operation takes as input (an index, a node pointer, or a pointer to the predecessor), because the costs differ by input. Finish by saying which questions you would ask about the workload before choosing, and give a recommendation for at least two different workloads.

Hints

Hint 1

Separate the cost of finding a position from the cost of changing the structure once you are there. Write the two costs separately for every operation.

Hint 2

For a resizable array, think about an append sequence rather than a single append: a rare expensive copy is spread across many cheap ones. Also think about what happens to existing pointers and iterators when the buffer moves.

Hint 3

For the unrolled list, ask what happens to the number of pointer hops, the number of allocations, and the cache lines touched, and then check whether jumping to index i becomes constant time. It does not.