TheScalableDev
Data StructuresBeginner45 minhead insert O(1) · insert or delete at a known node O(1) · access and search O(n)Free

Linked List - Insert at Head

Status

Nodes and pointers, singly versus doubly versus circular lists, why access is O(n) but splicing is O(1), dummy nodes, and the five pointer-rewiring moves (insert, delete, reverse, find the middle, detect a cycle) traced by hand and run in Node.

BestO(1)AverageO(n)WorstO(n)SpaceO(1)

A linked list is a treasure hunt. Each clue (a node) holds one prize (the value) and tells you where the next clue is hidden (the next pointer). You are only ever given the first clue, the head. To reach the tenth prize you must follow nine clues in order; there is no shortcut and no street numbering. The upside is that changing the hunt is cheap: to add a clue you rewrite one note, and to remove a clue you change the previous note so it skips the removed one. Nothing else moves. Almost every linked list problem is about rewriting those notes in the right order without ever losing the note that tells you where the REST of the hunt goes.

Builds on

  • Arrays in memory — a linked list is defined by how it differs from a contiguous array, so you should know why array indexing is O(1) and array insertion shifts elements.
  • Big-O notation — every operation below gets a derived cost such as O(1) or O(n), and we compare them against arrays.
  • Recursion basics — the recursive reverse uses the call stack as hidden storage, and you should understand base cases.
01

The problem: a sequence that changes shape

Suppose you keep a playlist and the songs live in an array. The first song is in slot 0, the second in slot 1, and so on, packed side by side. Now you want to slide a new song into the second position. Every song from that position onward has to move one slot to the right to open a gap, and if the array is full you must also allocate a bigger block and copy everything. The array is superb at 'give me item number 7' but clumsy when the sequence keeps changing shape in the middle.

A linked list drops the idea that neighbors must sit next to each other in memory. Instead every item lives in its own small object called a node, and each node carries two things: its value, and a pointer (in JavaScript, a reference) to the next node. The last node's pointer is null, which means 'nothing follows'. The entire list is identified by one variable, the head, which points at the first node. If the head is null the list is empty.

head
10
20
30
A three-node list. The head variable points at 10; 10 points at 20; 20 points at 30; 30's next is null (the arrow stops).

Because positions are not numbers but chains of pointers, there is no formula for 'the address of item 7'. To reach item 7 you start at the head and follow next pointers seven times. That single fact drives every complexity in this lesson: anything that needs to find a place by position or by value costs a walk, and anything that only touches the spot you are already holding costs a couple of pointer writes.

Here is the node and the smallest possible list in JavaScript. Notice that the 'list' is nothing more than a reference to the first node; there is no container object holding a length or an array of items unless you choose to add one.

A node and a three-element list built by hand.
1class Node {
2 constructor(value, next = null) {
3 this.value = value;
4 this.next = next;
5 }
6}
7
8const head = new Node(10, new Node(20, new Node(30)));
9console.log(head.value, head.next.value, head.next.next.value); // 10 20 30
10console.log(head.next.next.next); // null

Check yourself

What identifies a singly linked list as a whole in your program?

02

Singly, doubly and circular lists

The plain list above is singly linked: each node knows only its successor. That is the version interviewers mean unless they say otherwise, and it has a sharp limitation: you can only move forward. If you are standing on a node and want to remove it, you cannot reach the node before it, and that predecessor is exactly the node whose pointer must change.

A doubly linked list adds a second pointer, prev, to every node. Now from any node you can step backward, and you can unlink a node you are holding with no search at all: tell the previous node to skip forward past you and tell the next node to point back past you. The price is one extra pointer of memory per node and four pointer writes to splice instead of two, with more ways to leave the two directions disagreeing if you forget one write.

A circular list makes the last node point back at the first instead of at null. There is no end, so traversal loops need a different stopping rule (stop when you return to where you started). Rings are natural for round-robin schedulers and for buffers that wrap around. Notice that an accidental cycle in a list you thought was linear is a bug, and detecting it is a famous interview question, covered later.

VariantPointers per nodeWalk backwardRemove a node you holdTypical use
singly linkednextNoNeeds the predecessor: O(n) to find it, then O(1)Stacks, simple queues, interview problems
doubly linkednext and prevYesO(1): both neighbors are reachable from the nodeLRU caches, editors, deques
circular singlynext (last wraps to first)NoSame as singly, but no null endRound-robin rotation, ring buffers
circular doublynext and prev, both wrappingYesO(1)Sentinel-headed rings, playlists on repeat
Choose the variant by the operations you need, not by habit.

Check yourself

Why can a doubly linked list remove a node you are holding in O(1) when a singly linked list cannot?

03

Memory layout: why lists and arrays behave differently

An array reserves one contiguous block. The address of item i is the start address plus i times the slot size, so the machine computes it with one multiply and one add and jumps straight there. That is why array access is O(1). A linked list allocates nodes one at a time wherever the allocator finds room, so consecutive list nodes can sit far apart in memory and no arithmetic can predict where the next one is. The only way to learn the address of the next node is to read it out of the current node.

head
10
20
30
40
Logically adjacent, physically anywhere: each arrow stands for an address stored inside the node, not for distance in memory.

Walking such a chain is called pointer chasing, and it has two costs that Big-O notation does not show. First, each step depends on the previous step: the processor cannot start loading node 3 until node 2 has arrived and revealed where node 3 lives, so it cannot overlap the loads. Second, processors fetch memory in chunks called cache lines and keep recently used chunks in a small fast cache. Scanning an array touches neighbors that came along in the same chunk, and the hardware can also guess that you will want the following chunks. Scattered nodes enjoy far less of this help, so each hop is more likely to wait on slower memory.

The honest conclusion is qualitative: a linked list and an array can both be O(n) to scan, yet the array scan is usually the faster of the two in practice because of locality. We deliberately give no multiplier here, since it depends on the machine, the allocator and how the nodes were created. If nodes were allocated back to back they may happen to sit near each other, but you cannot rely on that after many inserts and deletes.

Memory overhead is easy to count if we state our assumptions. Assume a 64-bit machine where a pointer is 8 bytes and a stored value is also 8 bytes, and ignore allocator bookkeeping and language object headers (JavaScript engines add their own, so treat this as a model, not a measurement).

array of 1,000,000 values: 1,000,000 x 8 bytes = 8,000,000 bytes singly linked: 1,000,000 x (8 value + 8 next) = 16,000,000 bytes doubly linked: 1,000,000 x (8 value + 8 next + 8 prev) = 24,000,000 bytes
Under these assumptions a singly linked list needs twice the array's memory, and a doubly linked list three times.

The ratio changes with the payload. If each value is a large record of, say, 200 bytes, the 8-byte pointer is a small tax. If each value is a single small number, the pointer can be as large as the data it carries. That is part of the answer to 'when would you use a linked list': rarely when you store small values and mostly scan them, more plausibly when you hold node references and splice often.

Check yourself

Which statement about scanning a linked list versus an array of the same length is the most accurate?

04

Operations and their derived costs

Let n be the number of nodes. We derive each cost by counting pointer reads and writes, never by memorizing a table.

  • Access the kth node

    start at the head and follow next k times. That is k hops, up to n - 1 in the worst case, so it is O(n). There is no index to jump with.

  • Search for a value

    walk from the head comparing as you go. Worst case the value is last or absent, so n comparisons: O(n).

  • Insert at the head

    create a node, set its next to the old head, then set head to the new node. Two writes, no walking: O(1), independent of n.

  • Delete the head: set head to head.next. One write: O(1).

  • Insert after a node you hold

    set new.next to node.next, then node.next to new. Two writes: O(1). Getting that node is a separate cost.

  • Delete after a node you hold: set node.next to node.next.next. One write: O(1).

The tail is where design choices appear. With only a head pointer, appending means walking n - 1 hops to find the last node, so it is O(n). If you also store a tail pointer, append is O(1): write tail.next, then move tail. Deleting the tail is still O(n) in a singly linked list, because you need the second-to-last node to set its next to null, and the only way to find it is to walk. A doubly linked list with a tail pointer makes that O(1), since tail.prev is the predecessor.

OperationSingly, head onlySingly, head and tailDoubly, head and tailDynamic array
Access by positionO(n)O(n)O(n)O(1)
Search by valueO(n)O(n)O(n)O(n)
Insert at headO(1)O(1)O(1)O(n), shifts everything
Append at tailO(n), walkO(1)O(1)O(1) amortized
Delete headO(1)O(1)O(1)O(n), shifts everything
Delete tailO(n), need predecessorO(n), need predecessorO(1)O(1)
Insert or delete at a node you holdInsert after: O(1). Delete: needs predecessor, so O(n) unless you have itSameO(1)O(n), shifts the REST
Costs derived from pointer reads and writes. 'A node you hold' means you already have the reference; finding it by position or value costs O(n) first.

A useful sanity check is to count work in pointer writes. Insert after a node: 2 writes. Delete after a node: 1 write. Reverse a list of n nodes: n writes to flip every next, plus the walking. Every remaining question is how many hops it takes to get into position.

Check yourself

In a singly linked list with head and tail pointers, which operation is still O(n)?

05

Dummy nodes: removing the special case for the front

Almost every pointer rewrite has the form 'change prev.next'. The first real node has no previous node, so a naive solution needs an extra branch: if the thing you are changing is the head, then update the head variable; otherwise update prev.next. That branch is where bugs live, and it is easy to forget in a rush.

A dummy node (also called a sentinel) is a throwaway node created before the loop whose next points at the real head. Now every real node, including the first one, has a predecessor, so a single code path works. When you finish, return dummy.next as the new head. If the head was deleted or replaced, dummy.next already reflects it.

Delete the first node holding a value. No special case for the head, and an empty list needs no check either.
1function deleteValue(head, value) {
2 const dummy = new Node(null, head);
3 let prev = dummy;
4 while (prev.next !== null && prev.next.value !== value) prev = prev.next;
5 if (prev.next !== null) prev.next = prev.next.next;
6 return dummy.next;
7}

The same trick builds new lists. To collect nodes into a result, keep a dummy and a tail variable that starts at the dummy: append by writing tail.next and then advancing tail. At the end, the answer is dummy.next whether you appended zero, one or many nodes. You will use exactly this shape for merging two sorted lists. In a doubly linked circular design, a single sentinel can serve both as head and tail marker so that no pointer is ever null, a design often used to avoid null checks entirely.

Check yourself

You delete the node holding value 1 from the list 1 -> 2 -> 3 using a dummy node. What does the function return?

06

The five pointer-rewiring techniques

Nearly every linked list problem is a combination of five small moves. The Trace tab animates them in sequence on one list, 1 -> 2 -> 3 -> 4 -> 5; here is each move in words and in the order of its writes.

  1. 01Insert after a node

    Hold node cur. Create new. Write new.next = cur.next first, so the new node already points at the REST. Then write cur.next = new. Reversing these two writes makes new point at itself or loses the tail.

  2. 02Delete a node

    Hold the predecessor prev. Write prev.next = prev.next.next. The removed node is now unreachable and gets garbage collected. Never walk to the node itself and then try to remove it; you need the node before it.

  3. 03Reverse

    Keep prev (initially null) and cur (initially head). Each round: save next = cur.next, flip cur.next = prev, then advance prev = cur and cur = next. When cur becomes null, prev is the new head.

  4. 04Find the middle

    Start slow and fast at the head. Move slow one step and fast two steps while fast and fast.next exist. When fast cannot move, slow is at the middle.

  5. 05Detect a cycle

    Run slow and fast the same way. If the list has a loop, fast never reaches null and eventually lands on the same node as slow. If fast reaches null, there is no cycle.

Reverse is the one to master, because its safe order is the whole lesson in miniature. After cur.next = prev you have destroyed the only pointer to the REST of the list, so you must have saved cur.next into a variable one line earlier. Here is the state on the list 1 -> 2 -> 3 -> 4 -> 5 after three rounds, where the first three nodes already point backward. The diagram draws the reversed part first and then the untouched part; the arrow between the groups is only drawing layout, since node 1 now points to null and node 3 is what prev holds.

prev
3
2
1
cur
4
5
Reverse after three rounds: 3 -> 2 -> 1 -> null is done; 4 -> 5 is still untouched. prev is the head of the reversed part, cur is the head of the rest.

Why do slow and fast work? For the middle: in the time fast covers the whole list at two steps per round, slow covers half. For an odd length of 5, fast stops at the last node after 2 rounds, when slow sits at the third node. For an even length of 6 with the standard loop condition, slow ends on the second of the two middle nodes (value 4). If an interviewer wants the first middle, they usually say so, and you adjust the loop to stop one step earlier.

Why does cycle detection terminate? Once both walkers are inside the loop, fast gains exactly one node on slow per round (it moves 2 while slow moves 1). The gap, measured around the ring, shrinks by 1 each round, so it reaches 0 within at most the loop's length rounds. Fast can never jump over slow, because the gap changes by exactly one each round. Space is O(1), compared with a hash set of visited nodes that costs O(n) extra space.

Check yourself

In the iterative reverse, why must you save cur.next before writing cur.next = prev?

07

Implementation in JavaScript, iterative and recursive

Below is the whole toolkit in one file: build and print helpers, insert, delete, access, reverse (both ways), middle, cycle detection and remove-nth-from-end. We ran it in node and the printed output is shown under the code. Every line of output is explained by the earlier sections.

A complete linked list toolkit. Run with Node.
1class Node {
2 constructor(value, next = null) {
3 this.value = value;
4 this.next = next;
5 }
6}
7
8// Build 1 -> 2 -> ... from an array. A dummy node removes the empty-list case.
9function fromArray(values) {
10 const dummy = new Node(null);
11 let tail = dummy;
12 for (const v of values) {
13 tail.next = new Node(v);
14 tail = tail.next;
15 }
16 return dummy.next;
17}
18
19function toArray(head) {
20 const out = [];
21 for (let cur = head; cur !== null; cur = cur.next) out.push(cur.value);
22 return out;
23}
24
25// O(1): the two writes, in this order.
26function insertAfter(node, value) {
27 node.next = new Node(value, node.next);
28}
29
30// O(1) given the node BEFORE the target.
31function deleteAfter(prev) {
32 if (prev.next !== null) prev.next = prev.next.next;
33}
34
35// O(n): walk to the kth node (0-based). Returns null if the list is too short.
36function getAt(head, k) {
37 let cur = head;
38 for (let i = 0; i < k && cur !== null; i++) cur = cur.next;
39 return cur;
40}
41
42// Delete the first node holding value; the dummy makes head deletion uniform.
43function deleteValue(head, value) {
44 const dummy = new Node(null, head);
45 let prev = dummy;
46 while (prev.next !== null && prev.next.value !== value) prev = prev.next;
47 if (prev.next !== null) prev.next = prev.next.next;
48 return dummy.next;
49}
50
51function reverseIterative(head) {
52 let prev = null;
53 let cur = head;
54 while (cur !== null) {
55 const next = cur.next; // 1. save the rest
56 cur.next = prev; // 2. flip the arrow
57 prev = cur; // 3. advance prev
58 cur = next; // 4. advance cur
59 }
60 return prev;
61}
62
63function reverseRecursive(head) {
64 if (head === null || head.next === null) return head;
65 const newHead = reverseRecursive(head.next);
66 head.next.next = head; // the node after head now points back at head
67 head.next = null;
68 return newHead;
69}
70
71// Second middle for even lengths.
72function middle(head) {
73 let slow = head;
74 let fast = head;
75 while (fast !== null && fast.next !== null) {
76 slow = slow.next;
77 fast = fast.next.next;
78 }
79 return slow;
80}
81
82function hasCycle(head) {
83 let slow = head;
84 let fast = head;
85 while (fast !== null && fast.next !== null) {
86 slow = slow.next;
87 fast = fast.next.next;
88 if (slow === fast) return true;
89 }
90 return false;
91}
92
93// Remove the nth node from the end (1 = last) using a dummy and a gap of n.
94function removeNthFromEnd(head, n) {
95 const dummy = new Node(null, head);
96 let lead = dummy;
97 let trail = dummy;
98 for (let i = 0; i < n; i++) lead = lead.next;
99 while (lead.next !== null) {
100 lead = lead.next;
101 trail = trail.next;
102 }
103 trail.next = trail.next.next;
104 return dummy.next;
105}
106
107let list = fromArray([1, 2, 3, 4, 5]);
108console.log('built', toArray(list));
109insertAfter(getAt(list, 1), 9);
110console.log('insert 9 after index 1', toArray(list));
111deleteAfter(getAt(list, 1));
112console.log('delete it again', toArray(list));
113console.log('middle of 5', middle(list).value);
114console.log('middle of 6', middle(fromArray([1, 2, 3, 4, 5, 6])).value);
115list = deleteValue(list, 1);
116console.log('delete head value 1', toArray(list));
117list = fromArray([1, 2, 3, 4, 5]);
118console.log('reverse iter', toArray(reverseIterative(fromArray([1, 2, 3, 4, 5]))));
119console.log('reverse rec', toArray(reverseRecursive(fromArray([1, 2, 3, 4, 5]))));
120console.log('remove 2nd from end', toArray(removeNthFromEnd(fromArray([1, 2, 3, 4, 5]), 2)));
121console.log('remove last of one', toArray(removeNthFromEnd(fromArray([7]), 1)));
122console.log('cycle before', hasCycle(list));
123getAt(list, 4).next = getAt(list, 2);
124console.log('cycle after tail -> node 3', hasCycle(list));

The output of that script, exactly as node printed it:

Output
1built [ 1, 2, 3, 4, 5 ]
2insert 9 after index 1 [ 1, 2, 9, 3, 4, 5 ]
3delete it again [ 1, 2, 3, 4, 5 ]
4middle of 5 3
5middle of 6 4
6delete head value 1 [ 2, 3, 4, 5 ]
7reverse iter [ 5, 4, 3, 2, 1 ]
8reverse rec [ 5, 4, 3, 2, 1 ]
9remove 2nd from end [ 1, 2, 3, 5 ]
10remove last of one []
11cycle before false
12cycle after tail -> node 3 true

Iterative versus recursive reverse. The loop version uses three variables and O(1) extra space. The recursive version trusts the call to reverse everything after head, then fixes up one link: the node after head must now point back at head (head.next.next = head), and head becomes the new end (head.next = null). It is elegant and short, but the call stack holds one frame per node, so extra space is O(n), and a very long list can overflow the stack. In an interview, write the loop version first because it has no depth risk, and offer the recursive version if asked or if the problem naturally decomposes (for example, comparing a list to its mirror).

Removing the nth from the end shows a third idea: a gap of fixed length. Move a lead pointer n steps ahead of a trail pointer that starts at the dummy, then advance both until lead is on the last node. Now trail is exactly the predecessor of the node to delete, reached in a single pass. In the output, n = 2 on 1..5 removes the 4. The dummy lets n equal the length work, which removes the head, as in the single-node case that printed [].

Check yourself

What is the extra space of the recursive reverse on a list of n nodes?

08

Common bugs and how to defend against them

linked list code is short, so mistakes are about order and boundaries rather than complex logic. These four account for most failures in practice and in interviews.

BugHow it happensSymptomDefense
Losing the REST of the listOverwriting a next pointer before saving the old value, such as cur.next = prev in reverse with no saved nextList is silently truncated; later nodes vanishName the node you will need next (next = cur.next) before any rewrite
null dereferenceReading .next on null: fast.next.next with fast.next null, or walking past the tailTypeError: cannot read properties of nullCheck fast and fast.next before the double step; guard every .next chain
Off-by-one from the endMoving the lead pointer n steps but starting from head instead of the dummy, or stopping at null instead of the last nodeDeletes the wrong node, or fails when n equals the lengthUse a dummy, move lead n steps, then loop while lead.next is not null
Stale head or tailDeleting or inserting the first or last node without updating the head or tail variableCaller still sees a removed node; later appends go to a dead nodeReturn the new head; update tail when deleting the last node; use a dummy
Accidental cycleWiring a node to itself, or reusing a node in two lists without cutting itInfinite loop on traversalSet the old next to null when moving a node; test with a short loop guard
Failure modes of linked list code and their fixes.

The insert-at-head example from the older version of this lesson captures the first class of bug perfectly. If you write head = newNode before newNode.next = head, the new node's next points at itself, and the old list is lost. The safe order is always: build the new links while the old ones still exist, and publish them (move head or prev.next) last.

Check yourself

Your slow and fast loop is written while (fast.next !== null) { ... fast = fast.next.next }. Which input crashes it?

09

Versus arrays, and where lists show up for real

QuestionLinked listArray / dynamic array
Access item kO(k) walkO(1) arithmetic
Insert or delete at the frontO(1)O(n) shift
Insert or delete at a position you already holdO(1) (doubly linked, or after a held predecessor)O(n) shift
Append at the endO(1) with a tail pointerO(1) amortized
Memory per elementValue plus one or two pointers, plus object overheadValue only, with spare capacity at the end
Memory layoutScattered nodes, pointer chasingContiguous, cache friendly
GrowthOne node at a time, no copying of existing nodesOccasionally allocate a larger block and copy
Existing node references after an insertRemain validMay be invalidated by a resize in some languages
Choose by the dominant operation. When in doubt, an array wins; justify a list with a specific splicing need.

Where do linked structures appear in real software? Stated generally, with only claims we are confident about:

  • LRU caches

    a hash map from key to node, plus a doubly linked list ordered by recency. A lookup finds the node in O(1) through the map, and moving it to the front is a constant-time splice because the node knows both neighbors. The lru-cache lesson builds this.

  • Graph adjacency lists

    each vertex keeps a chain of its neighbors; adding an edge is a cheap insertion at the front of one chain.

  • Undo and history

    a chain of states where undoing moves backward and redoing moves forward, naturally modeled by a doubly linked list.

  • Hash table chaining

    many hash tables resolve collisions by keeping a short linked list of entries per bucket.

  • Free lists in allocators

    an allocator can thread unused blocks together so that allocating pops the head and freeing pushes onto it, both O(1). The links are often stored inside the free blocks themselves, which is the intrusive idea.

  • Queues and stacks

    a linked stack is just head insertion and head deletion; a linked queue uses a head and a tail pointer.

Check yourself

Why do LRU cache designs pair a hash map with a doubly linked list instead of using only an array?

10

Interview problems this unlocks

Each classic problem is one of the five moves, sometimes plus a dummy node. Use this map to pick the right tool in the first minute.

Problem lessonCore technique from this lessonWhy it fits
reverse-linked-listReverse with prev, cur, nextThe canonical rewiring exercise; both loop and recursion are expected
merge-two-sorted-listsdummy node plus tail appendBuild the result by appending the smaller head each time, then attach the leftover
linked-list-cycleslow and fast pointersA loop makes fast catch slow; O(1) space
remove-nth-node-from-end-of-listDummy plus a gap of nOne pass, deleting through the predecessor
reorder-listFind middle, reverse second half, mergeCombines three moves from this lesson
merge-k-sorted-listsMerge two lists, extended by a heapRepeats the dummy and tail pattern across many lists
LRU-cachedoubly linked list plus hash mapO(1) splice of a held node
design-hashmapChaining with linked bucketsCollisions stored as short lists
pattern-fast-slow-pointersThe pattern lesson for the two-speed walkGeneralizes the middle and cycle moves
The right-hand column is the technique to name out loud.

Use the same script every time. Minute 0 to 2: restate the problem and assumptions (singly linked? length unknown? values unique? can I mutate?). Minute 2 to 5: draw the list on paper with two or three nodes and choose a technique from the table. Minute 5 to 15: code it, starting with a dummy if the front can change. Minute 15 to 20: trace an empty list, a single node, and the largest-risk case by hand, then state the time and space cost.

  1. 01Clarify and assume

    Singly or doubly linked, can the list be empty, and is mutation allowed. Say the assumptions aloud.

  2. 02Draw and pick the move

    Sketch 1 -> 2 -> 3 and mark the pointers you will rewrite. Name the technique.

  3. 03Code with a dummy if the head can change

    Protect every .next access with a null check, and save the node you will need before you redirect a pointer.

  4. 04Trace the edge cases

    Empty, one node, two nodes, and the case where the target is the head or the tail.

  5. 05State complexity

    Time is the number of hops; space is the extra variables, or the call stack if you recursed.

Check yourself

Which combination of moves solves reorder-list (L0, L1, ..., Ln becomes L0, Ln, L1, Ln-1, ...)?

Recap

  • A node is a value plus a next pointer; the list is just the head pointer. An empty list is a null head.

  • Access by position and search are O(n) because you must walk from the head. Insert or delete at the head, or right after a node you already hold, is O(1): two pointer writes.

  • Deleting a node in a singly linked list needs its predecessor. Finding the predecessor is the O(n) part, not the unlinking.

  • A tail pointer makes append O(1). A doubly linked list makes removing a known node O(1) at the price of one more pointer per node.

  • A dummy node in front of the head removes the special case for the first node, in the same way for insert, delete, merge and remove-nth.

  • rewire in an order that never drops the only reference to the REST of the list: save next, then redirect, then advance.

  • slow and fast pointers find the middle (fast reaches the end when slow is halfway) and detect cycles (a fast walker must eventually land on a slow one inside a loop).

  • Linked lists lose to arrays on cache behavior because nodes scatter across memory. They win when you hold node references and splice often, which is why LRU caches pair a hash map with a doubly linked list.

Terms in this lesson

Every acronym and concept, expanded. Tap a term to open it.

time complexity

How an algorithm's number of operations grows with input size.

cycle detection

Finding whether a graph or linked structure contains a loop, classically with fast/slow pointers.

two pointers

Moving two indices through an array to meet a condition in one pass instead of nested loops.

linked list

A chain of nodes where each points to the next, giving cheap inserts and deletes but O(n) access.

call stack

The stack of active function calls the runtime tracks; each recursive call adds a frame.

merge sort

A divide-and-conquer sort that splits, sorts halves recursively, and merges them in O(n log n).

palindrome

A string that reads the same forward and backward.

amortized

Averaged over many operations, so an occasional expensive step is charged against many cheap ones.

recursion

A function that calls itself with a smaller version of the same problem until it hits a base case.

invariant

A property that stays true throughout an algorithm, used to prove it correct.

hash map

A key-value store using a hash function for average O(1) lookups, inserts, and deletes.

hash set

A hash map that stores only keys, used to answer 'have I seen this?' in O(1).

Big-O

Notation that describes how an algorithm's work grows as its input grows, ignoring constants and hardware.

array

A contiguous block of memory holding items in order, readable by index in O(1).

graph

A set of nodes connected by edges, with no tree-shaped restriction.

RESTRepresentational State Transfer

An API style built on plain HTTP verbs (GET, POST, PUT, DELETE) where each URL names a resource.

node

One box in the list: a value plus a pointer to the next box.

A clue card in a treasure hunt.

LRUleast recently used

A cache eviction rule that discards the entry that has gone unused the longest.

Clearing the book that has sat untouched on your desk the longest.

bit

A single 0 or 1 - the smallest unit of data.

pointer

A field that holds the location of another node, or null if there is none. In JavaScript it is an object reference.

The address written on the clue card.

head

The first node. It is the only entry point; every other node is reached by following next pointers.

The first clue you are handed.

tail

The last node, whose next pointer is null. Keeping a separate tail pointer makes appending O(1).

The final clue that says the hunt is over.

null

The value meaning 'no node here'. It marks the end of a list and an empty list is just a null head.

singly linked

Each node has only a next pointer, so you can only walk forward.

doubly linked

Each node has next and prev pointers, so you can walk both ways and unlink a known node without searching for its predecessor.

circular

The last node points back to the first instead of to null, so the chain forms a ring.

dummy node

A throwaway node placed before the real head (also called a sentinel) so that inserting or deleting at the front uses the same code as anywhere else.

A starting line painted before the first runner.

rewire

Changing next pointers to splice nodes in or out or to flip direction.

pointer chasing

Following one pointer after another, where the address of each step is only known after the previous step finished loading.

cache

Small fast memory close to the processor that holds recently used data, loaded in chunks called cache lines.

cache locality

The benefit of touching data that sits close together in memory, because one load brings its neighbors along for free.

heap

The region of memory where objects are allocated at run time, in no promised order or position.

slow and fast pointers

Two walkers over the same list, one moving one node per step and the other two, used to find the middle and to detect cycles.

A tortoise and a hare on a track.

cycle

A chain in which following next pointers eventually returns to an already visited node, so the walk never reaches null.

intrusive list

A design where the link pointers live inside the objects being stored, instead of in separate wrapper nodes.

Where you will see it

Real systems that use this exact idea. Tap a card to open it.

Common traps

The mistakes interviewers watch for. Guess the fix, then reveal it.

  1. FixMoving head first makes newNode.next point at itself, an instant cycle, and the old list is lost. Set newNode.next = head first, then move head.

  2. FixThat write destroys the only reference to the rest of the list. Save next = cur.next first, then flip, then advance.

  3. FixThe splice is O(1) only when you already hold the node. Reaching position k from the head costs k hops, so insert at an index is O(k) overall.

Interview prep

Questions you could be asked, with the depth an interviewer wants to hear.

Access and search are O(n) because you walk from the head. Insert or delete at the head is O(1): a couple of pointer writes. Insert or delete at a node you already hold is O(1) once you have the predecessor; finding it is the O(n) part. Append is O(1) only with a tail pointer.

access O(n) · splice O(1)

Real worldThis is why a queue backed by a list keeps both head and tail references.

DeeperThen ask yourself what the cost is if the node must be found by value first: O(n) for the search plus O(1) for the splice.