Linked Lists

A chain of items where each one points to the next, instead of sitting side by side in memory.

What is it?

An array packs items together in memory: fast to read, slow to insert into. In a linked list, each item (a node) stores its value plus a pointer to the next node. Nodes can sit anywhere in memory; the pointers connect them.

The trade-off is the opposite of an array's. Inserting or removing a node is fast (change a couple of pointers). But finding the 5th item means walking through the first four; you can't jump to a position.

Explain like I'm 10

A linked list is like a scavenger hunt: each clue tells you where the next one is. You can't jump to clue #5; you follow the chain from the start. But adding a new clue in the middle is easy: point the previous clue somewhere new.

Examples

A simple linked list in JavaScript

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

const first = new Node(10);
const second = new Node(20);
first.next = second; // 10 → 20

console.log(first.value);      // 10
console.log(first.next.value); // 20

How it works

Each node holds a value and a reference to the next node (null for the last one). To read position 5, start at the first node and follow .next five times. Unlike an array, you can't calculate the memory location directly.

[10] → [20] → [30] → null
 head

To reach 30: head → next → next

Why does it exist?

Linked lists suit programs that insert and remove a lot (especially at the front or middle) and don't need fast access by position. They're also the foundation for structures like stacks and queues.

When to use it

Use a linked list when you insert and remove often, especially at the front or middle, and never need to jump to a position by index.

When not to use it

Avoid it if you need frequent access by index (get the 500th item): that's O(n) here versus O(1) in an array. Plain arrays cover most everyday JavaScript needs. Use a linked list mainly to build another structure (a queue, a stack) or when a problem calls for one.

Common mistakes

  • Forgetting to update the next pointer when inserting a node, which breaks the chain.

  • Overwriting a next pointer before saving it, which loses the rest of the list.

  • Assuming linked lists have fast random access like arrays. They don't.

Practice exercises

  1. Easy:

    Build a linked list of 3 nodes by hand and print each value by following .next.

  2. Medium:

    Write a function that returns the length of a linked list by traversing it.

  3. Hard:

    Write a function that reverses a singly linked list in place, without creating a new list.

Interview questions

What's the main trade-off between arrays and linked lists?

Arrays give O(1) access by index but O(n) insertion/removal in the middle, since later elements shift. Linked lists give O(1) insertion/removal (given a reference to the node) but O(n) access by position, since you can't jump to an index.

What is a node?

The basic unit of a linked list: an object holding a value and a pointer (or pointers) to neighboring nodes.

What's the difference between a singly and doubly linked list?

Singly linked nodes point only to next, so you can only go forward. Doubly linked nodes also point to prev, so you can go both ways, at the cost of one extra pointer (and its upkeep) per node.

Why is inserting at the front of a linked list O(1), while inserting at the front of an array is O(n)?

For a linked list, create a node and point it at the old head; nothing else moves. For an array, every element shifts one slot right, touching all n elements.

Why is finding the nth element O(n) in a linked list but O(1) in an array?

An array computes the address from the index (base address + index × element size). A linked list has no formula; you follow next pointers one at a time from the head.

What is a circular linked list, and what's it useful for?

A list whose last node's next points back to the first instead of null, forming a loop. It suits things that cycle, like round-robin scheduling or a repeating playlist, where you keep advancing without hitting an end.

What is Floyd's cycle detection algorithm, and how does it detect a cycle using O(1) extra space?

Also called 'tortoise and hare'. Move slow one node at a time and fast two at a time. If there's a cycle, fast laps slow and they land on the same node. If not, fast reaches null first. It uses only two pointers, so O(1) space.

Why must the fast and slow pointers eventually meet if there's a cycle, instead of just missing each other forever?

Once both are in the loop, fast closes the gap by exactly one node per step (it moves 2, slow moves 1). A gap shrinking by 1 each step in a finite loop must reach 0, so they can't skip past each other.

Once Floyd's algorithm finds a meeting point, how do you find the exact node where the cycle begins?

Reset one pointer to the head, leave the other at the meeting point, and advance both one node at a time. They meet again at the start of the cycle. This follows from the distances between the head, the cycle start and the meeting point.

Walk through reversing the list `1 -> 2 -> 3 -> null` iteratively using three pointers (`prev`, `current`, `next`).

Start with prev = null, current = head (node 1). Each iteration: save next = current.next, set current.next = prev (reverse the link), then prev = current and current = next. After node 1: 1 -> null, prev=1. After node 2: 2 -> 1 -> null, prev=2. After node 3: 3 -> 2 -> 1 -> null, prev=3, current=null. The loop ends and prev is the new head.

How would you reverse a singly linked list recursively, and how does its complexity compare to the iterative version?

Recurse to the end first. As each call returns, point the next node's next back at the current node and set the current node's next to null. Both are O(n) time, but recursion uses O(n) stack space versus O(1) for the iterative version.

What's a common bug when reversing a linked list iteratively?

Setting current.next = prev before saving the original current.next. The rest of the list becomes unreachable, so the reversal silently truncates it.

What is a sentinel (dummy) head node, and why does it simplify list code?

A placeholder node kept before the real head; its value is never used. The real first node is then always some node's .next, so inserting or removing at the front needs no special case.

How would you find the middle node of a linked list in a single pass, without first counting its length?

Start slow and fast pointers at the head. Move slow one node and fast two nodes per step. When fast reaches the end (or null), slow is on the middle node, having covered half the distance.

Why does a queue built on a singly linked list need both a `head` and a `tail` pointer to keep both operations O(1)?

Dequeue only needs head. Without tail, enqueue must walk the whole list to find the last node: O(n). A tail pointer lets you attach the new node in O(1).

What's a subtle bug when removing a node from the middle of a singly linked list?

You need the previous node, not just the node itself, because removal updates the previous node's next to skip it. Forgetting to track the previous node is a common cause of broken removal.

There's a trick to 'delete' a node given only a reference to it (no access to the previous node): copy the next node's value into it, then skip over the next node. Why does this fail for the last node in the list?

The trick turns the target into a copy of its successor, then removes the successor. The last node has no successor to copy from or skip, so the trick can't work.

How would you find where two singly linked lists intersect (merge into a shared tail), in O(n + m) time and O(1) extra space?

Find both lengths. Advance the pointer on the longer list by the difference, so both are the same distance from the end. Then move both one node at a time; the first node where they're the same reference is the intersection.

How would you remove the nth node from the end of a linked list in a single pass?

Start fast and slow at a dummy head before the real head, and move fast n nodes ahead. Then move both together until fast reaches the end. slow is now just before the target, so slow.next = slow.next.next removes it.

How would you merge two already-sorted linked lists into a single sorted list, and what's the time complexity?

Walk both lists with two pointers, attaching the smaller current node to the result and advancing that list. When one runs out, attach the rest of the other. O(n + m) time, since each node is visited once, and O(1) extra space if you re-link existing nodes.

How would you check whether a linked list is a palindrome, ideally using O(1) extra space?

Find the middle with slow/fast pointers, reverse the second half in place, then compare the first half with the reversed second half. All matching means it's a palindrome. This avoids an O(n) array copy but temporarily changes the list (you can restore it afterwards).

What's the extra memory cost of a doubly linked list compared to a singly linked list, per node?

One extra pointer per node (prev), typically 8 bytes on a 64-bit system, plus the work of keeping it correct on every insert and remove.

Why do a doubly linked list and a hash map together form the backbone of a classic LRU cache implementation?

The hash map finds a key's node in O(1). The doubly linked list keeps nodes in recency order, and since each node knows both neighbors, it can remove a node from anywhere and re-insert it at the front in O(1). That moves a just-used item to the 'most recent' end without scanning.

Why does a linked list have worse cache locality than an array, even though both are O(n) to traverse?

Array elements are contiguous, so the CPU can prefetch ahead. Linked list nodes are usually scattered across separate heap allocations, so following next jumps around memory and causes more cache misses, despite the same Big O.

What memory overhead does a linked list carry per element compared to a plain array of the same values?

Each node needs at least one pointer (next, plus prev if doubly linked) on top of the value, and is usually its own heap allocation with allocator bookkeeping. An array stores values back to back with no per-element pointer.

What is a circular doubly linked list, and where is it used?

A doubly linked list where the last node's next points to the first and the first node's prev points to the last, forming a loop you can walk either way. It's used in looping playlists and some LRU caches, where wrapping around avoids special cases at the ends.

What happens if a traversal loop's condition is `while (node.next)` instead of `while (node)`?

The loop stops as soon as node.next is null, so the body never runs for the last node. It's silently skipped, with no null-pointer error.

Scenario: you're designing an LRU cache needing O(1) `get` and O(1) `put`. Why is a hash map or array alone insufficient?

A hash map gives O(1) lookup but can't track recency order or evict the least-recently-used item without scanning. An array tracks order but costs O(n) to move an item to the front or remove one from the middle. A hash map (O(1) lookup) plus a doubly linked list (O(1) reordering and eviction at either end) gives both.

What's the time complexity of accessing the head, the tail, and an arbitrary middle element of a singly linked list with only a head pointer?

Head: O(1), it's referenced directly. Tail: O(n), you walk the whole list. Middle: O(n), you follow next pointers from the head.