Courses / DSA Patterns for Working Engineers / Chapter 6
Module 2 · Pointers, windows, intervals and linked lists · Chapter 6 of 39
In-Place Linked List Changes: Reversal, Reordering and Rotation
Builds on Fast and Slow Pointers: Cycles, Midpoints and Repeats. Next up: Heaps and Two Heaps: Running Medians and Priority Scheduling.
Part 1 · Introduction to in-place list changes
What in place means
Playlists, rosters, undo histories and conveyor schedules are often stored as linked lists, and a common job is to reshape one without building a new copy. Doing that with only a few extra variables, no matter how long the list is, is called working in place.
A linked list stores each item in a node that holds a value and a reference to the next node. The fast and slow pointers chapter defined the ListNode class used throughout this course, and the code below is the same class with its two helpers: fromArray builds a list from an array and toArray reads one back.
export class ListNode { val: number next: ListNode | null constructor(val: number, next: ListNode | null = null) { this.val = val this.next = next } } export function fromArray(xs: number[]): ListNode | null { let head: ListNode | null = null for (let i = xs.length - 1; i >= 0; i--) { head = new ListNode(xs[i], head) } return head } export function toArray(head: ListNode | null): number[] { const out: number[] = [] for (let n = head; n; n = n.next) out.push(n.val) return out }
ListNode, fromArray and toArray
In-place work means changing the next references of existing nodes, never copying the list or moving values between nodes. One helper node, such as the dummy head described below, is allowed, because its size does not depend on the list. The cost of such a change is measured in two numbers: time, which is usually O(n) because every node is visited once, and extra space, which is the memory used beyond the list itself. The target for this chapter is O(1) extra space: a fixed handful of references, whatever the length.
Two habits keep the work safe. First, save before you overwrite. Every change replaces some next reference, and once it is replaced the rest of the list can be lost, so you hold the old value in a variable first. Second, use a dummy head: a throw-away node placed before the real head, so that the node before position 1 exists. Code that can change the head, such as reversing the first few nodes, then needs no special case, and at the end you return dummy.next.
The rewiring step
Reversing a list shows the whole technique. Walk down the list with three references. curr is the node being turned around, prev is the node already turned around that comes just before it in the new order, and next is the rest of the list that curr is about to lose. At each step: save next = curr.next, point curr.next at prev, move prev to curr, and move curr to the saved next. When curr is null, prev is the new head.
The scene draws each node as a cell showing its value and the value of the node it points to, with x meaning no next node. Nothing moves except the arrows.
Watch for each arrow turning back to the node behind it
Read it as steps
each node's next pointer is rewritten to point back at the node behind it
After the loop, the old head points at nothing and the old tail points at its former neighbour. Every node was visited once, and the only memory used was the three references. That is the shape of every in-place change in this chapter: a loop that saves, rewires and advances.
Iterative and recursive versions
Reversal can also be written recursively: reverse the list that starts at the second node, then make the second node point back to the first node, and cut the first node's own link. The two functions below do the same job.
import type { ListNode } from './list.ts' // Point each node at the one behind it. O(n) time, O(1) space. export function reverseIter(head: ListNode | null): ListNode | null { let prev: ListNode | null = null let curr = head while (curr) { const next = curr.next // save it before the link is overwritten curr.next = prev prev = curr curr = next } return prev } // Reverse the rest, then hang this node at the end. O(n) call stack. export function reverseRec(head: ListNode | null): ListNode | null { if (!head || !head.next) return head const newHead = reverseRec(head.next) head.next.next = head head.next = null return newHead }
Iterative reversal with O(1) space and recursive reversal
The recursive version looks short, but each call waits for the next one to finish, so a list of n nodes keeps n calls on the call stack at once. The stack has a fixed size, and when it is full JavaScript throws a RangeError. The program below reverses a short list both ways and then tries a list of 1,00,000 nodes.
import { fromArray, toArray } from './list.ts' import { reverseIter, reverseRec } from './reverse.ts' const xs = [4, 8, 15, 16] console.log('iterative:', toArray(reverseIter(fromArray(xs)))) console.log('recursive:', toArray(reverseRec(fromArray(xs)))) const long = Array.from({ length: 100_000 }, (_, i) => i) const out = toArray(reverseIter(fromArray(long))) console.log('iterative, 100000 nodes:', out.length) try { reverseRec(fromArray(long)) } catch (e) { console.log('recursive, 100000 nodes:', (e as Error).name) }
Both versions on four nodes, then on 1,00,000
iterative: [ 16, 15, 8, 4 ] recursive: [ 16, 15, 8, 4 ] iterative, 100000 nodes: 100000 recursive, 100000 nodes: RangeError
Output of one run
How deep the recursion can go
The iterative version has no such limit. How long a list can the recursive version handle? A binary search over lengths, repeated three times on Windows and three times in WSL on this machine, gave the same answer every time.
import { fromArray } from './list.ts' import { reverseRec } from './reverse.ts' // Largest list length that reverseRec handles, by binary search. function works(n: number): boolean { try { reverseRec(fromArray(Array.from({ length: n }, (_, i) => i))) return true } catch { return false } } let lo = 1 let hi = 1_000_000 while (lo < hi) { const mid = (lo + hi + 1) >>> 1 if (works(mid)) lo = mid else hi = mid - 1 } console.log('largest list reversed recursively:', lo)
Find the longest list reverseRec can handle
largest list reversed recursively: 9765The same number on Windows and WSL here; it varies with the function and the Node version
The limit depends on the function and the machine: how much stack each call uses decides it, so a different function or a different Node version gives a different limit. The one-argument function measured in the first chapter of the course stopped near 9,600 calls, a different count from a different function. Treat both as rough figures for Node 24 on this machine, not as a rule. The stack error is explained on MDN. A call that is the last thing a function does is a tail call, and some languages reuse the caller's stack frame for it, so tail recursion needs no extra stack. Node 24 does not, as the next run shows with a countdown in strict mode whose recursive call is its last action.
'use strict' // A call in tail position: nothing is left to do after it returns. function countdown(n: number): number { return n === 0 ? 0 : countdown(n - 1) } console.log(countdown(1000)) try { console.log(countdown(1_000_000)) } catch (e) { console.log((e as Error).name + ': ' + (e as Error).message) }
A tail call in strict mode still grows the stack
0
RangeError: Maximum call stack size exceededOutput of one run
So for long lists, use the loop. The recursive version is still a good way to understand the idea, but it is not O(1) space: it uses O(n) stack.
Related on LeetCode: Reverse Linked List.
Part 2 · Reversing a playback queue
The problem
A music app keeps the up-next queue as a linked list of song ids, first song to play at the head. A user taps "reverse queue" so that the last song added plays first. The list can be long, and the app does not want to allocate a second copy of it.
The easy answer is to copy the ids into an array, reverse the array and build a new list. It works, but it uses O(n) extra space and creates n new nodes, and any other code holding a reference to a node now holds a node that is no longer in the queue. Reversing in place keeps the same nodes and only changes where they point.
The loop from the previous lesson is already the answer, so this lesson spends its time on tracing it by hand and on what to test. A reversal function is short, and the bugs that matter live at its edges.
Tracing is the habit that catches most pointer bugs. The run below executes the loop on a queue of three song ids, 3, 1, 4, and prints the state after each step. done is the list that starts at prev, which is the reversed part so far.
import { ListNode, fromArray, toArray } from './list.ts' // reverseIter with a printout after every step. let prev: ListNode | null = null let curr = fromArray([3, 1, 4]) const show = (n: ListNode | null) => (n ? String(n.val) : 'null') while (curr) { const next: ListNode | null = curr.next curr.next = prev prev = curr curr = next const done = toArray(prev).join(' ') console.log(`prev ${show(prev)}, curr ${show(curr)}, done: ${done}`) }
The reversal loop with a printout per step
prev 3, curr 1, done: 3 prev 1, curr 4, done: 1 3 prev 4, curr null, done: 4 1 3
Output of one run
After the first step the reversed part is just 3, whose next is now null. After the second it is 1, 3, and after the third it is 4, 1, 3 with curr at null, which ends the loop. Notice that done always starts at prev: the reversed part grows at its front, one node at a time, which is why the new head is prev and not curr.
The tests
import test from 'node:test' import assert from 'node:assert/strict' import { fromArray, toArray } from './list.ts' import { reverseIter } from './reverse.ts' test('an empty queue stays empty', () => { assert.equal(reverseIter(null), null) }) test('one song is its own reverse', () => { assert.deepEqual(toArray(reverseIter(fromArray([7]))), [7]) }) test('the order flips', () => { const reversed = reverseIter(fromArray([3, 1, 4, 1, 5])) assert.deepEqual(toArray(reversed), [5, 1, 4, 1, 3]) }) test('the same nodes are reused, not copied', () => { const head = fromArray([1, 2, 3]) const reversed = reverseIter(head) assert.equal(reversed?.next?.next, head) assert.equal(head?.next, null) }) test('a long queue does not overflow the stack', () => { const big = Array.from({ length: 200_000 }, (_, i) => i) const out = toArray(reverseIter(fromArray(big))) assert.equal(out[0], 199_999) assert.equal(out.length, 200_000) })
Empty, single, ordinary, node identity and long queues
✔ an empty queue stays empty (0.612ms) ✔ one song is its own reverse (0.6782ms) ✔ the order flips (0.1469ms) ✔ the same nodes are reused, not copied (0.1609ms) ✔ a long queue does not overflow the stack (30.7764ms) ℹ tests 5 ℹ pass 5 ℹ fail 0
Output of one run; the times in brackets vary
Read the tests as a list of promises. An empty queue returns null, which holds because the loop never runs and prev starts as null. A single song is returned as it is: its next is overwritten with null, which it already was. The order test uses a repeated id, 1, to show that the function works on positions and not on values. The identity test proves the function is in place: after reversal the first node you had is now the last one and points at nothing, and the new head's second-next is that original head. The last test builds 2,00,000 nodes and reverses them with no stack problem, which is the property the recursive version cannot offer.
Costs and variations
The reversal makes one pass, so it costs O(n) time. It uses the three references prev, curr and next, so extra space is O(1). Nothing in it depends on the values in the list, so the same code reverses a queue of numbers, ids or any other payload.
Three variations are common. First, to check whether a list reads the same forwards and backwards, you can reverse its second half, compare the halves and put the half back, as the fast and slow pointers chapter did. Second, to read a list in reverse without changing it, you can push the values on a stack or an array, but that costs O(n) space. Third, to reverse only part of a list or reverse it in blocks, you need to reconnect the reversed part to the rest. Those are the next two lessons, and both rely on this loop.
A caution about shared nodes. Reversing in place changes the structure that every holder of those nodes can see. If two lists share a tail, reversing one of them corrupts the other. Code that must not disturb other holders should copy first, and code that is allowed to change the list should say so in its name or its comment.
Related on LeetCode: Reverse Linked List.
What does the identity test in the suite prove?
- The same node objects are reused, so the reversal is in place and not a copy.
- The old head ends up last and points at
null.
A teammate reverses a queue in place while another feature still holds a pointer to the old head. What does that feature now see?
- Only the old head and nothing after it, because the old head is now the last node.
- In-place changes affect every holder of the nodes.
What are the time and extra space of the loop?
- O(n) time and O(1) extra space.
Part 3 · Reversing one stretch of coaches
The problem
A train is stored as a linked list of coach numbers from the engine backwards. Maintenance has to turn coaches at positions m to n around, for example because a section of the train is being reversed on a siding, while every other coach stays attached in its place. Positions are counted from 1 at the head.
You could split the list into three parts, reverse the middle part with the previous lesson's loop and join the three parts. That works, but it needs care at both joins and more than one pass over some nodes. There is a neater way that does everything in one pass using the dummy head from the first lesson.
Pull each node to the front
Find the node before that sits just ahead of position m. The node currently at position m, call it first, will end up last in the reversed stretch. Now repeat n minus m times: take the node right after first, unhook it from there, and insert it directly after before. Each repeat moves one node to the front of the stretch, so after n minus m repeats the stretch is in reverse order and first is last in it, still pointing at whatever followed position n.
Look at what the three assignments do. first.next = move.next removes move from its old place. move.next = before.next makes it point at the current front of the stretch. before.next = move makes it the new front. The order matters, because each line uses a value that a later line overwrites.
The dummy head matters when m is 1. With no node before position 1, the loop would need a special case. A dummy node before the head gives before something to hold, and dummy.next is the answer whether or not the head changed.
The code
import { ListNode } from './list.ts' // Reverse the nodes at positions m..n (1-based, 1 <= m <= n <= length). export function reverseBetween( head: ListNode | null, m: number, n: number, ): ListNode | null { if (!head || m >= n) return head const dummy = new ListNode(0, head) // a node before position 1 let before = dummy for (let i = 1; i < m; i++) before = before.next as ListNode const first = before.next as ListNode // ends up last in the stretch for (let i = m; i < n; i++) { const move = first.next as ListNode first.next = move.next // unhook the node after first move.next = before.next // put it at the front of the stretch before.next = move } return dummy.next }
Reverse positions m to n in one pass
Before reading the function, watch the pull-to-front step on a list of six coaches with m = 3 and n = 5. The run prints the list after each node is moved to the front of the stretch.
import { ListNode, fromArray, toArray } from './list.ts' // The pull-to-front loop of reverseBetween for positions 3 to 5. const head = fromArray([41, 42, 43, 44, 45, 46]) const dummy = new ListNode(0, head) const before = (dummy.next as ListNode).next as ListNode // position 2 const first = before.next as ListNode // the node at position 3 console.log('start: ', toArray(dummy.next).join(' ')) for (let i = 3; i < 5; i++) { const move = first.next as ListNode first.next = move.next move.next = before.next before.next = move console.log(`moved ${move.val}:`, toArray(dummy.next).join(' ')) }
Two pull-to-front moves for positions 3 to 5
start: 41 42 43 44 45 46 moved 44: 41 42 44 43 45 46 moved 45: 41 42 45 44 43 46
Output of one run
The first move takes 44, which sat right after first (43), and puts it at the front of the stretch, right after before (42). The second takes 45, which now sits right after 43 again, and puts it in front of 44. Coach 43 is never picked up: it drifts to the back of the stretch as the others are pulled ahead of it, and it ends pointing at 46, the node that followed position 5.
The function assumes 1 <= m <= n <= length. It returns early when m >= n, since reversing zero or one node changes nothing. The first loop walks m - 1 steps to find before, and the second loop runs n - m times. Together that is at most n steps, so time is O(n) and extra space is O(1).
import test from 'node:test' import assert from 'node:assert/strict' import { fromArray, toArray } from './list.ts' import { reverseBetween } from './between.ts' const run = (xs: number[], m: number, n: number) => toArray(reverseBetween(fromArray(xs), m, n)) test('a stretch in the middle flips, the rest stays', () => { const xs = [11, 12, 13, 14, 15, 16] assert.deepEqual(run(xs, 3, 5), [11, 12, 15, 14, 13, 16]) }) test('m at the head changes the head', () => { assert.deepEqual(run([11, 12, 13, 14], 1, 3), [13, 12, 11, 14]) }) test('n at the tail', () => { assert.deepEqual(run([11, 12, 13, 14], 2, 4), [11, 14, 13, 12]) }) test('the whole list', () => { assert.deepEqual(run([11, 12, 13], 1, 3), [13, 12, 11]) }) test('m equal to n changes nothing', () => { assert.deepEqual(run([11, 12, 13], 2, 2), [11, 12, 13]) }) test('an empty list', () => { assert.equal(reverseBetween(null, 1, 1), null) })
Middle, head, tail, whole list, m equal to n and empty
Checking against arrays
A model on a plain array is easy to write: take the elements before m, the reversed slice from m to n, and the elements after n. The check below compares the list version with that model on random lists and random m and n. It also checks the k-group function from the next lesson, which is why it imports both.
import { mulberry32 } from './rng.ts' import { fromArray, toArray } from './list.ts' import { reverseGroups } from './groups.ts' import { reverseBetween } from './between.ts' // The same two operations on a plain array, as the reference. function groupsRef(xs: number[], k: number): number[] { const out = xs.slice() for (let i = 0; i + k <= out.length; i += k) { out.splice(i, k, ...out.slice(i, i + k).reverse()) } return out } function betweenRef(xs: number[], m: number, n: number): number[] { const middle = xs.slice(m - 1, n).reverse() return [...xs.slice(0, m - 1), ...middle, ...xs.slice(n)] }
The array models of the two operations
const rand = mulberry32(11) const pick = (lo: number, hi: number) => lo + Math.floor(rand() * (hi - lo + 1)) let bad = 0 for (let t = 0; t < 3000; t++) { const xs = Array.from({ length: pick(1, 12) }, () => pick(0, 99)) const k = pick(1, 14) const m = pick(1, xs.length) const n = pick(m, xs.length) const g = toArray(reverseGroups(fromArray(xs), k)) const b = toArray(reverseBetween(fromArray(xs), m, n)) if (g.join() !== groupsRef(xs, k).join()) bad++ if (b.join() !== betweenRef(xs, m, n).join()) bad++ } console.log(`3000 random lists, ${bad} differences`)
Three thousand random lists, one pass each
3000 random lists, 0 differences
Output of one run
No differences. If one had appeared, the first thing to look at would be the smallest failing list printed with its m and n, and a hand trace of the three assignments on it.
Related on LeetCode: Reverse Linked List II.
In the pull-to-front step, why must first.next = move.next come before move.next = before.next?
- The first line unhooks
movewhilefirst.nextstill points at it. - Done in the other order, the link to the rest of the list would be overwritten and lost.
Part 4 · Reversing parcels in batches of k
The problem
Parcels travel on a conveyor, stored as a linked list. The sorter has to reverse every complete batch of k parcels, so the first k come out in reverse order, then the next k, and so on. If fewer than k parcels remain at the end, they are left alone.
This is the stretch reversal repeated, once per batch. Calling reverseBetween for each batch would walk from the head every time to find the batch, which makes the total quadratic. Instead, keep before pointing at the node just ahead of the next batch and carry it forward. Then each batch is walked twice, once to check that it is complete and once to reverse it, and the whole list costs O(n).
The loop
For each batch:
- Walk k steps from
beforeto see whether k nodes remain. If not, stop: the tail stays as it is. - Take
first = before.next, the node that will end up last in the batch. - Do the pull-to-front step k minus 1 times.
- Move
beforetofirst, which is now the last node of the batch and the node just ahead of the next one.
The run below applies the same loop to ten parcels with k = 4 and prints the list after each batch. The last two parcels never move.
import { ListNode, fromArray, toArray } from './list.ts' // reverseGroups for k = 4, printing the list after each full batch. const k = 4 const parcels = fromArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) const dummy = new ListNode(0, parcels) let before = dummy for (let batch = 1; ; batch++) { let probe: ListNode | null = before for (let i = 0; i < k && probe; i++) probe = probe.next if (!probe) { console.log('fewer than 4 nodes left: stop') break } const first = before.next as ListNode for (let i = 1; i < k; i++) { const move = first.next as ListNode first.next = move.next move.next = before.next before.next = move } before = first console.log(`after batch ${batch}:`, toArray(dummy.next).join(' ')) }
The batch loop for k = 4 with a printout per batch
after batch 1: 4 3 2 1 5 6 7 8 9 10 after batch 2: 4 3 2 1 8 7 6 5 9 10 fewer than 4 nodes left: stop
Output of one run
The scene runs this on eight nodes with k = 3. Cells show each node's value and the value it points to.
Watch for each full group of three flipping while the last two stay
Read it as steps
The code
import { ListNode } from './list.ts' // Reverse every full group of k nodes; a short tail stays as it is. export function reverseGroups( head: ListNode | null, k: number, ): ListNode | null { if (k < 2) return head const dummy = new ListNode(0, head) let before = dummy for (;;) { let probe: ListNode | null = before for (let i = 0; i < k && probe; i++) probe = probe.next if (!probe) break // fewer than k nodes are left const first = before.next as ListNode for (let i = 1; i < k; i++) { const move = first.next as ListNode first.next = move.next move.next = before.next before.next = move } before = first // first is now the last node of this group } return dummy.next }
Reverse every full group of k nodes
The guard k < 2 returns the list unchanged because a group of one is its own reverse. The probe loop is the completeness check, and it moves at most k steps for each batch. Time is O(n) in total and extra space is O(1).
import test from 'node:test' import assert from 'node:assert/strict' import { fromArray, toArray } from './list.ts' import { reverseGroups } from './groups.ts' const run = (xs: number[], k: number) => toArray(reverseGroups(fromArray(xs), k)) const parcels = [21, 22, 23, 24, 25, 26, 27] test('k = 1 changes nothing', () => { assert.deepEqual(run(parcels, 1), parcels) }) test('k = 2 swaps neighbours and leaves the odd one', () => { assert.deepEqual(run(parcels, 2), [22, 21, 24, 23, 26, 25, 27]) }) test('k = 3 flips two groups and leaves the short tail', () => { assert.deepEqual(run(parcels, 3), [23, 22, 21, 26, 25, 24, 27]) }) test('k = the length reverses the whole list', () => { assert.deepEqual(run(parcels, 7), [27, 26, 25, 24, 23, 22, 21]) }) test('k larger than the list changes nothing', () => { assert.deepEqual(run(parcels, 8), parcels) }) test('an empty list', () => { assert.equal(reverseGroups(null, 3), null) })
k of 1, 2, 3, the length, more than the length, and empty
✔ k = 1 changes nothing (1.3752ms) ✔ k = 2 swaps neighbours and leaves the odd one (0.1063ms) ✔ k = 3 flips two groups and leaves the short tail (0.1138ms) ✔ k = the length reverses the whole list (0.1288ms) ✔ k larger than the list changes nothing (0.1497ms) ✔ an empty list (0.1382ms) ℹ tests 6 ℹ pass 6 ℹ fail 0
Output of one run; the times in brackets vary
The tests show the edge cases: k equal to 1 changes nothing, k larger than the list changes nothing because no batch is complete, and k equal to the list length is plain reversal. With k equal to 2 the function swaps neighbours in pairs and leaves a single last parcel alone. That special case, swapping nodes in pairs, is common enough to be a named problem.
Part 5 · Reordering a duty roster
The problem
A duty roster is a linked list of staff ids. The manager wants an alternating order: the first person, then the last, then the second, then the second last, and so on until everyone is placed. For 1, 2, 3, 4, 5, 6 that gives 1, 6, 2, 5, 3, 4. The change must be in place.
Reading the target order, the odd positions of the answer come from the front of the list in order and the even positions come from the back of the list in reverse order. A list cannot be read backwards, but a reversed half can. So the plan has three steps, and each is a tool you already have.
- Find the middle with a slow and a fast pointer, as in the fast and slow pointers chapter. Stop
slowat the last node of the first half. - Reverse the second half with the loop from the first lesson, after cutting the list in two by setting
slow.next = null. - Weave the two lists together, taking one node from the first half, then one from the reversed second half, and repeating.
For odd lengths, the first half is one node longer, so the middle node is left at the end, as in 1, 7, 2, 6, 3, 5, 4 for a roster of seven.
The code
import type { ListNode } from './list.ts' import { reverseIter } from './reverse.ts' // First, last, second, second-last, ... changed in place. export function reorder(head: ListNode | null): void { if (!head || !head.next) return let slow = head // stops at the end of the first half let fast = head while (fast.next && fast.next.next) { slow = slow.next as ListNode fast = fast.next.next } let second = reverseIter(slow.next) // back half, reversed slow.next = null let first: ListNode | null = head while (second && first) { const a: ListNode | null = first.next const b: ListNode | null = second.next first.next = second // weave one from each half second.next = a first = a second = b } }
Split at the middle, reverse the back half, weave
The while loop for the middle stops when fast.next.next is missing, which puts slow at the end of the first half for both odd and even lengths. In the weave, a and b save the next node of each half before the links change. The loop ends when the reversed half runs out. Total time is O(n) from three passes, and extra space is O(1).
The run below shows the steps on a roster of seven. The middle is the fourth node, because the first half keeps the extra node when the length is odd.
import { fromArray, toArray } from './list.ts' import { reverseIter } from './reverse.ts' import { reorder } from './reorder.ts' // The steps of reorder on a roster of 7, printed in turn. const head = fromArray([1, 2, 3, 4, 5, 6, 7])! let slow = head let fast = head while (fast.next && fast.next.next) { slow = slow.next! fast = fast.next.next } console.log('middle (end of first half):', slow.val) const back = reverseIter(slow.next) slow.next = null console.log('first half:', toArray(head).join(' ')) console.log('back half reversed:', toArray(back).join(' ')) const whole = fromArray([1, 2, 3, 4, 5, 6, 7]) reorder(whole) console.log('woven:', toArray(whole).join(' '))
The steps on seven names
middle (end of first half): 4 first half: 1 2 3 4 back half reversed: 7 6 5 woven: 1 7 2 6 3 5 4
Output of one run
The first half is 1, 2, 3, 4 and the reversed back half is 7, 6, 5. Weaving takes 1, then 7, then 2, then 6, then 3, then 5, and the leftover 4 stays last. The weave stops when the back half runs out, because the first half is never shorter than the back half.
Odd-even regrouping
A related change keeps positions rather than values: put all nodes at odd positions first and all nodes at even positions after them, each group in its original order. Two references walk the list, one over odd positions and one over even positions, and each hops over the node of the other kind. When they are done, the odd chain's tail is joined to the saved head of the even chain.
// Positions 1, 3, 5, ... first, then positions 2, 4, 6, ... export function oddEven(head: ListNode | null): ListNode | null { if (!head || !head.next) return head let odd = head let even = head.next const evenHead = even while (even && even.next) { odd.next = even.next odd = odd.next even.next = odd.next even = even.next as ListNode } odd.next = evenHead return head }
Positions 1, 3, 5 first, then 2, 4, 6
The name refers to position, not to the value stored in the node, which is why the test uses values such as 7, 4, 9, 2, 5 that do not match their positions.
import test from 'node:test' import assert from 'node:assert/strict' import { fromArray, toArray } from './list.ts' import { reorder, oddEven } from './reorder.ts' const weave = (xs: number[]) => { const head = fromArray(xs) reorder(head) return toArray(head) } const split = (xs: number[]) => toArray(oddEven(fromArray(xs))) test('an odd roster: the middle name ends up last', () => { assert.deepEqual(weave([8, 3, 6, 1, 9]), [8, 9, 3, 1, 6]) }) test('an even roster alternates ends', () => { assert.deepEqual(weave([1, 2, 3, 4, 5, 6]), [1, 6, 2, 5, 3, 4]) }) test('zero, one and two names stay as they are', () => { assert.deepEqual(weave([]), []) assert.deepEqual(weave([9]), [9]) assert.deepEqual(weave([9, 8]), [9, 8]) }) test('odd-even groups positions, not values', () => { assert.deepEqual(split([7, 4, 9, 2, 5]), [7, 9, 5, 4, 2]) assert.deepEqual(split([7, 4, 9, 2]), [7, 9, 4, 2]) assert.deepEqual(split([5, 6]), [5, 6]) assert.deepEqual(split([]), []) })
Odd and even lengths, tiny lists and the regrouping
✔ an odd roster: the middle name ends up last (1.0995ms) ✔ an even roster alternates ends (0.1418ms) ✔ zero, one and two names stay as they are (0.1136ms) ✔ odd-even groups positions, not values (0.1364ms) ℹ tests 4 ℹ pass 4 ℹ fail 0
Output of one run; the times in brackets vary
To get more confidence, compare both functions with array models on thousands of random lists, along with the rotation from the next lesson.
import { mulberry32 } from './rng.ts' import { fromArray, toArray } from './list.ts' import { reorder, oddEven } from './reorder.ts' import { rotateRight } from './rotate.ts' // Plain-array versions of the three list operations. function reorderRef(xs: number[]): number[] { const out: number[] = [] for (let i = 0, j = xs.length - 1; i <= j; i++, j--) { out.push(xs[i]) if (i !== j) out.push(xs[j]) } return out } const oddEvenRef = (xs: number[]) => [ ...xs.filter((_, i) => i % 2 === 0), ...xs.filter((_, i) => i % 2 === 1), ] const rotateRef = (xs: number[], k: number) => { const s = xs.length === 0 ? 0 : k % xs.length return s === 0 ? xs : [...xs.slice(-s), ...xs.slice(0, -s)] }
Array versions of the three operations
Part 6 · Rotating a round-robin roster
The problem
A round-robin roster of on-call engineers is a linked list. At the end of each shift the last k engineers move to the front, so the list rotates right by k. A rotation by k can be much larger than the list: a script might say rotate by 6,00,001 even though the roster has six people.
Rotating one step at a time, moving the last node to the front k times, costs O(k times n), which is far too slow for a large k. The shortcut is that rotating by the length of the list brings you back to the start, so only k mod length matters. Here mod is the remainder after division: for six people, 10 mod 6 is 4.
The plan
Rotating right by shift = k mod length means the last shift nodes become the front. In terms of links, only two things change. The node at position length - shift becomes the new last node, and its next is cut to null. The old last node's next is set to the old head. The node after the cut is the new head.
So the algorithm has two walks. The first walk finds the length and the tail together. The second walks length - shift - 1 steps from the head to the new tail. If shift is zero, there is nothing to do and the head is returned as it is.
Take the six-person roster 1 to 6 and a rotation of 10. The run below computes the reduced shift and where the cut falls before it shows the rotated list.
import { fromArray, toArray } from './list.ts' import { rotateRight } from './rotate.ts' const roster = [1, 2, 3, 4, 5, 6] const k = 10 const length = toArray(fromArray(roster)).length const shift = k % length console.log(`length ${length}, k ${k}, shift ${shift}`) console.log('new last node sits at position', length - shift) const turned = rotateRight(fromArray(roster), k) console.log('result:', toArray(turned).join(' '))
Length, shift and the cut position for k = 10
length 6, k 10, shift 4 new last node sits at position 2 result: 3 4 5 6 1 2
Output of one run
The shift is 4, so the last four people, 3, 4, 5 and 6, move to the front. The new last node is the one at position 2, and the cut falls right after it.
The code
import type { ListNode } from './list.ts' // Move the last k nodes to the front. Works for any k >= 0. export function rotateRight( head: ListNode | null, k: number, ): ListNode | null { if (!head || !head.next) return head let length = 1 let tail = head while (tail.next) { tail = tail.next length++ } const shift = k % length // a full turn changes nothing if (shift === 0) return head let newTail = head for (let i = 1; i < length - shift; i++) { newTail = newTail.next as ListNode } const newHead = newTail.next as ListNode newTail.next = null // cut after the new last node tail.next = head // join the old end to the old front return newHead }
Rotate right by k with a count pass and a cut pass
The early return handles an empty list and a list of one node, where every rotation gives the same list. The line k % length is the heart of the function. The cost is O(n) time, for two passes, and O(1) extra space.
import test from 'node:test' import assert from 'node:assert/strict' import { fromArray, toArray } from './list.ts' import { rotateRight } from './rotate.ts' const roster = [1, 2, 3, 4, 5, 6] const run = (k: number) => toArray(rotateRight(fromArray(roster), k)) test('k = 0 and k = length change nothing', () => { assert.deepEqual(run(0), roster) assert.deepEqual(run(6), roster) }) test('k = 1 moves the last name to the front', () => { assert.deepEqual(run(1), [6, 1, 2, 3, 4, 5]) }) test('k = 4 moves the last four', () => { assert.deepEqual(run(4), [3, 4, 5, 6, 1, 2]) }) test('k larger than the list wraps with k mod length', () => { assert.deepEqual(run(10), run(4)) assert.deepEqual(run(600_001), run(1)) }) test('empty and single-name rosters', () => { assert.equal(rotateRight(null, 3), null) assert.deepEqual(toArray(rotateRight(fromArray([7]), 3)), [7]) })
k of 0, 1, 4, the length, more than the length and tiny lists
✔ k = 0 and k = length change nothing (1.2738ms) ✔ k = 1 moves the last name to the front (0.1228ms) ✔ k = 4 moves the last four (0.0841ms) ✔ k larger than the list wraps with k mod length (0.1122ms) ✔ empty and single-name rosters (0.1142ms) ℹ tests 5 ℹ pass 5 ℹ fail 0
Output of one run; the times in brackets vary
Two tests are worth a closer look. The test for k = 0 and k = 6 checks that a whole turn changes nothing, which is the case the shift === 0 check handles: without it the new last node would be the old tail, the new head would be null, and joining the tail to the head would turn the list into a loop. A copy with the check removed returned null for 1, 2, 3 rotated by 3. The test with 6,00,001 compares against k = 1 on the six-person roster, since 6,00,001 mod 6 is 1. The large number checks that only k mod length matters, and the same stress check from the previous lesson compared rotation with an array model on random lists.
All chapters · Previous: Intervals: Merging, Inserting and Counting Overlaps