Skip to the page

Linear patterns · mid

Linked lists

A linked list is nodes with next pointers, so problems are about re-wiring pointers safely: keep a reference before you overwrite next, use a dummy head for edge cases, and use fast and slow pointers for the middle and for cycles.

The notes

What you must know

  • Reverse: prev = null; while cur: next = cur.next; cur.next = prev; prev = cur; cur = next; return prev.
  • A dummy head node removes special cases when the head changes (merge, remove elements).
  • Fast and slow: slow moves 1, fast moves 2. The middle is slow when fast reaches the end; a cycle exists if they meet (Floyd), using O(1) extra space.
  • Copy a list with a random pointer: a hash map from old node to new node in two passes, or interleave the copies for O(1) extra space.
  • LRU cache in O(1): a hash map from key to node plus a doubly linked list ordered by use. A get or put moves the node to the front; when full, remove the node at the back. Library shortcuts exist (Java LinkedHashMap in access order, Python OrderedDict.move_to_end), but interviewers often ask for the manual version.
  • In C++ free removed nodes (or use smart pointers); in Java and Python the garbage collector does it. In Java a built-in LinkedList is rarely faster than ArrayList: get(i) is O(n).

The red pen

Common traps: mistake → fix

  • Mistake: Set cur.next = prev first

    Fix: you lose the rest of the list; save next before re-wiring.

  • Mistake: Handle the empty list later

    Fix: a null head breaks most loops; test the empty list and a list of one node.

  • Mistake: Cycle detection needs a set of visited nodes

    Fix: Floyd's algorithm needs O(1) space.

Easy to hard

Questions interviewers ask, easy to hard

  1. Reverse a linked list, iteratively and recursively.
  2. Find the middle node in one pass.
  3. Detect a cycle with O(1) extra space.
  4. Copy a list with random pointers.
  5. Design an LRU cache with O(1) get and put.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview