TRT
Sign in
mediumFoundationsLeetCode#dummy head#size counter

Design linked list

Implement a linked list with get, add at head, add at tail, add at index and delete at index, handling every edge case.

The Runtime Theory Team1 min read
Taught inNodes and pointersA linked list is a chain of separately allocated nodes, each holding a value and the address of the next. Walking it is O(n), and rewiring it never moves a value.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inaddAtHead(1), addAtTail(3), addAtIndex(1, 2), get(1)

out2

inthen deleteAtIndex(1), get(1)

out3

inget(5) on a list of 2

out-1

Implement MyLinkedList with get(index), addAtHead(val), addAtTail(val), addAtIndex(index, val) and deleteAtIndex(index). Indexes are 0-based; invalid indexes return -1 from get and are ignored by the other operations.

Before you code

Every method needs "the node before position i". If you write one helper that returns it, the rest are a few lines each. The head is the only position without a node before it, unless you give it one.

Hints

  1. Keep a dummy head node and a size counter. Then addAtHead is addAtIndex(0, ...) and addAtTail is addAtIndex(size, ...).
  2. To reach the node before index i, start at the dummy and follow next i times.
  3. Validate the index against size before walking: 0 <= i <= size for adding, 0 <= i < size for get and delete.
  4. Variant: make it doubly linked with a tail pointer, so that addAtTail is O(1).

Production & complexity notes

When solving Design linked list on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Nodes and pointers to reinforce the underlying pattern.

What it practices

Building a list from nodes and next pointers, from Nodes and pointers, and the dummy head from the next lesson.

Not started

Sign in to save your learning progress.

Sign in to save