Home / Patterns / Linked Lists

Linked Lists Pattern Hub

7 problems

Linked List Cycle

easy
TC: O(N) · SC: O(1)

Floyd’s Tortoise & Hare: advance `slow` by 1 and `fast` by 2. Inside a cycle of length C, their relative gap decreases by 1 per step, guaranteeing collision inside <= C iterations.

LRU Cache

medium
TC: O(1) · SC: O(C)

Combine a HashMap (`key -> Node`) for O(1) lookup with an insertion/recency doubly-linked list (with dummy `head`/`tail` sentinels) so promotion to MRU and eviction from LRU both run in O(1).

Merge k Sorted Lists

hard
TC: O(N log k) · SC: O(1)

Either push the head of each non-empty list into a size-k min-heap (`O(N log k)` time, `O(k)` space) OR pairwise divide-and-conquer merge halves (`O(N log k)` time, `O(1)` extra heap allocations).

Merge Two Sorted Lists

easy
TC: O(N + M) · SC: O(1)

Anchor the output with a `dummy` sentinel node and a `tail` pointer. Repeatedly attach the smaller of `l1` and `l2`, then splice whichever tail remains non-null in O(1).

Remove Nth Node From End of List

medium
TC: O(N) · SC: O(1)

Attach a `dummy` before `head`. Advance `right` `n + 1` steps ahead of `left = dummy`, or advance `right` `n` steps then step both until `right.next == null` so `left` lands cleanly on the predecessor.

Reorder List

medium
TC: O(N) · SC: O(1)

Three O(1)-space primitives composed in sequence: (1) find middle via fast/slow pointers, (2) split (`slow.next = None`) and reverse the second half, (3) zipper-merge the two halves alternatingly.

Reverse Linked List

easy
TC: O(N) · SC: O(1)

Maintain `prev = None` and `curr = head`. Before reversing `curr.next = prev`, save `nxt = curr.next`, then advance `prev, curr = curr, nxt`. Return `prev`.