Courses / DSA Patterns for Working Engineers / Chapter 3
Module 2 · Pointers, windows, intervals and linked lists · Chapter 3 of 39
Fast and Slow Pointers: Cycles, Midpoints and Repeats
Builds on Two Pointers: Pairs, Partitions and In-Place Scans. Next up: Sliding Windows: Fixed and Variable Ranges Over Sequences.
Part 1 · Introduction to fast and slow pointers
A linked list and two speeds
A linked list stores items as nodes, each holding a value and a reference to the next node. Two pointers moving at different speeds solve several of its problems, such as loops and middles, with no extra memory.
A list gives no way to jump to the middle or to ask for its length without walking it. A damaged list can also loop back on itself, and a plain walk then runs forever. Both problems are where the two speeds pay off.
Here is the node class used for the rest of the course, with two helpers that convert between arrays and lists. The fields are assigned in the constructor, because Node only strips types and does not support parameter properties.
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 }
The idea is simple. A slow pointer moves one node per step and a fast pointer moves two. If the list ends, the fast pointer reaches the end first, and the walk stops. If the list contains a cycle, a stretch of nodes that links back to an earlier node, neither pointer ever reaches the end. Both end up circling inside the cycle, where the fast pointer gains one node per step on the slow one.
Why they must meet
Once both pointers are in the cycle, look at the gap between them, measured along the direction of travel. Each step the fast pointer moves two nodes and the slow one moves one, so the gap shrinks by exactly one. A gap that shrinks by one each step must reach zero, and a gap of zero means the pointers stand on the same node. The fast pointer cannot jump over the slow one, because the gap only ever drops from 1 to 0, never from 1 to minus 1.
Finding the entry
That settles detection. Finding the entry, the first node of the cycle, takes one more observation. Let the distance from the head to the entry be a, and let the cycle have c nodes. When the pointers meet, the slow one has walked a plus some distance b into the cycle, and the fast one has walked twice as far. The fast one has also made some whole number of extra laps, so twice the slow distance equals the slow distance plus a multiple of c. That leaves a + b equal to a multiple of c.
Now start a new pointer at the head and keep the other at the meeting point, both moving one node per step. The new pointer needs a steps to reach the entry. The pointer at the meeting point is b nodes past the entry, and a + b is a whole number of laps, so after a more steps it has come round to the entry too. They meet at the entry.
Watch for fast lapping slow inside the loop, then both meeting at its entry
Read it as steps
Fast laps slow in the loop, then two pointers meet at the entry
Labels show the latest round that stood on a node: s for slow and f for fast. In round 5 both land on node 5, inside the loop. The second phase starts one pointer at node 0 and keeps one at node 5, and after three steps each they meet on node 3, the entry. The tail has three nodes before the entry, and the loop has five.
Floyd's method on lists with different entries
The function below is Floyd's method, also called the tortoise and hare method. It returns the meeting node and the entry node.
export type Meeting = { meet: ListNode; entry: ListNode } | null // Floyd's method: slow moves 1 step, fast moves 2. export function floyd(head: ListNode | null): Meeting { let slow = head let fast = head while (fast && fast.next) { slow = (slow as ListNode).next fast = fast.next.next if (slow === fast) { // Restart one pointer at the head; both now move 1 step. let a = head as ListNode let b = slow as ListNode while (a !== b) { a = a.next as ListNode b = b.next as ListNode } return { meet: slow as ListNode, entry: a } } } return null }
To test it you need lists with a loop in a known place. The helper withLoop builds a list from an array and, when pos is not negative, links the last node back to the node at index pos.
// Builds a list and, when pos >= 0, links the tail back to node pos. export function withLoop(xs: number[], pos: number): ListNode | null { const head = fromArray(xs) if (pos < 0 || !head) return head let tail = head let target = head for (let i = 0; tail.next; i++) { if (i < pos) target = target.next as ListNode tail = tail.next } tail.next = target return head }
import { withLoop } from './list.ts' import { floyd } from './floyd.ts' const xs = [0, 1, 2, 3, 4, 5, 6, 7] for (const pos of [-1, 0, 3, 5, 7]) { const head = withLoop(xs, pos) const hit = floyd(head) const label = pos < 0 ? 'no loop' : `loop back to ${pos}` console.log( hit ? `${label}: met at ${hit.meet.val}, entry ${hit.entry.val}` : `${label}: fast reached the end`, ) }
no loop: fast reached the end loop back to 0: met at 0, entry 0 loop back to 3: met at 5, entry 3 loop back to 5: met at 6, entry 5 loop back to 7: met at 7, entry 7
An eight-node list 0 to 7, with the tail linked back to different positions
Each run agrees with the argument above: the entry is always the node the tail links to, and the meeting node varies. With a loop back to node 0 the pointers meet at the head, and with a loop back to node 7 the last node links to itself.
The cost is O(n) time, because the first phase takes at most n steps and the second phase takes a steps, and O(1) extra space, because only four references are kept. Compare that with the usual alternative, a Set of visited nodes, which is simple but takes O(n) space.
Part 2 · A loop in a hand-off chain
The problem
A courier network records each parcel hand-off as a node pointing to the next one. A bug can corrupt the log so that a late node points back to an earlier node, and any report that walks the chain then never finishes. The task has two parts: say whether the chain loops, and if so, return the first node of the loop.
The detection part is the first phase of Floyd's method. The pointers start at the head. Each round, slow moves one node and fast moves two. If fast or fast.next is null the chain ends and there is no loop. If the two references are the same node, there is one.
Compare node references, never values. Two different hand-offs can carry equal values, and a match on values would report a loop that does not exist.
Why not simply count steps and give up after a large number? A cutoff guesses: a legitimate chain longer than the cutoff would be reported as a loop, and a short loop would be noticed late. A set of visited nodes is exact but takes memory in proportion to the chain, which can be tens of lakhs of hand-offs. Two pointers are exact and use two references. For the second part, the entry, the previous lesson gave the argument: after the pointers meet, one restarts at the head and both move one node at a time.
Keep the two parts separate in your code. Many callers only need a yes or no, and for them the second phase is wasted work. The detection function below returns a boolean, and a second function returns the entry.
The code and its tests
// Is the hand-off chain corrupted into a loop? export function hasLoop(head: ListNode | null): boolean { let slow = head let fast = head while (fast && fast.next) { slow = (slow as ListNode).next fast = fast.next.next if (slow === fast) return true } return false }
// The first node of the loop, or null if there is none. export function loopStart(head: ListNode | null): ListNode | null { let slow = head let fast = head while (fast && fast.next) { slow = (slow as ListNode).next fast = fast.next.next if (slow === fast) { let a = head as ListNode let b = slow as ListNode while (a !== b) { a = a.next as ListNode b = b.next as ListNode } return a } } return null }
The loop condition checks fast and fast.next before the double step, so the second hop never reads a property of null. The empty chain fails the condition at once and returns no loop. A chain with one node that points to itself passes the condition, takes one round, and both pointers land on that node.
import test from 'node:test' import assert from 'node:assert/strict' import { ListNode, fromArray, withLoop } from './list.ts' import { hasLoop, loopStart } from './loop.ts' test('a straight chain has no loop', () => { const head = fromArray([1, 2, 3, 4]) assert.equal(hasLoop(head), false) assert.equal(loopStart(head), null) }) test('an empty chain has no loop', () => { assert.equal(hasLoop(null), false) }) test('a loop back to the head starts at the head', () => { const head = withLoop([1, 2, 3, 4], 0) assert.equal(loopStart(head), head) }) test('a self-loop is found', () => { const only = new ListNode(9) only.next = only assert.equal(hasLoop(only), true) assert.equal(loopStart(only), only) }) test('a loop in the middle starts where the tail links', () => { const head = withLoop([1, 2, 3, 4, 5, 6], 2) assert.equal(loopStart(head)?.val, 3) })
✔ a straight chain has no loop (0.7233ms) ✔ an empty chain has no loop (0.1122ms) ✔ a loop back to the head starts at the head (0.1011ms) ✔ a self-loop is found (0.0791ms) ✔ a loop in the middle starts where the tail links (0.1574ms) ℹ tests 5 ℹ pass 5 ℹ fail 0
One test run on this machine; the times vary
The five tests include the three cases that matter: no loop, a loop that begins at the head, and a self-loop. For the head case, the second phase starts both pointers at the head already when they meet there, and a !== b is false at once.
Measuring the loop
Once you hold a node on the loop, its length is the number of steps to come round to it again. This helper walks from the entry once.
// Length of the loop, found by walking once around it from node `at`. export function loopLength(at: ListNode): number { let n = 1 for (let p = at.next; p !== at; p = (p as ListNode).next) n++ return n }
import { withLoop } from './list.ts' import { loopStart, loopLength } from './loop.ts' const head = withLoop([10, 20, 30, 40, 50, 60, 70], 2) const start = loopStart(head) console.log(`loop starts at ${start?.val}`) console.log(`loop length ${start ? loopLength(start) : 0}`)
loop starts at 30 loop length 5
Seven nodes, with the tail linked back to the third
The list has seven nodes and the tail links to the third, so the loop is nodes 30, 40, 50, 60 and 70: five of them. The entry is 30, as the test also asserts.
Knowing the length is useful on its own. If a recovery job wants to repair the chain, it can cut the loop by finding the node just before the entry, the one whose next is the entry, and setting its next to null. Walk from the entry until you reach a node whose next is the entry, then clear that link. That repairs the chain in O(n) with the same two references.
Related on LeetCode: Linked List Cycle is the detection step, and Linked List Cycle II asks for the entry node.
Why compare nodes with === and not their values?
- Different nodes can hold equal values. Only the same node means the walk has come back to where it was.
What does the loop condition fast && fast.next protect against?
- Reading
.nexton null when the list ends, at either one or two steps from the end.
A teammate writes the condition as fast.next && fast. Which chains break it, and how?
Part 3 · The middle stop of a bus route
Finding the middle in one pass
A bus route is stored as a list of stops. The operator wants the middle stop, without counting the stops first and walking a second time. The two speeds give it directly. When the fast pointer has covered the whole list, the slow one has covered half of it.
Start both at the head. While fast and fast.next exist, move slow one node and fast two. For a list of five stops, fast stops on the last node and slow stands on the third. For a list of four stops, fast falls off the end after two rounds and slow stands on the third node, which is the second of the two middle stops. A route of one stop returns that stop, and an empty route returns null.
| Stops | Slow ends on | Why |
|---|---|---|
| 1 | Stop 1 | fast.next is null, so the loop never runs |
| 4 | Stop 3 | two rounds: fast falls off the end after the second |
| 5 | Stop 3 | two rounds: fast reaches the last node |
| 6 | Stop 4 | three rounds: fast falls off the end |
When the count is even there are two middle stops, and this loop returns the second.
// Middle stop; for an even count, the second of the two middles. export function middle(head: ListNode | null): ListNode | null { let slow = head let fast = head while (fast && fast.next) { slow = (slow as ListNode).next fast = fast.next.next } return slow }
If a problem wants the first of the two, stop one round earlier by testing fast.next && fast.next.next. That condition reads fast.next straight away, so an empty route has to be handled before the loop.
Twin sums of mirrored stops
A second question uses the middle. The twin of a stop is the stop at the mirrored position from the other end: the first and last stops are twins, the second and second-last, and so on. For a route with an even number of stops, which is the largest sum of a stop and its twin?
Two pointers moving in opposite directions would solve this on an array, but a list cannot be walked backwards. So reverse the second half, which starts at the middle node. Now one pointer starts at the head and another at the head of the reversed half. Walk both forward together: each pair is a stop and its twin.
Reversing a list in place takes three references: the previous node, the current node and the next node. Each step points the current node back at the previous one. The in-place linked list chapter covers reversal in detail, and the function below uses the plain loop.
// Largest sum of a stop and its mirror (even-length route). export function maxTwinSum(head: ListNode | null): number { let mid = middle(head) // reverse the second half let prev: ListNode | null = null while (mid) { const next: ListNode | null = mid.next mid.next = prev prev = mid mid = next } let best = 0 let a = head as ListNode for (let b = prev; b; b = b.next) { best = Math.max(best, a.val + b.val) a = a.next as ListNode } return best }
Tests
import test from 'node:test' import assert from 'node:assert/strict' import { fromArray } from './list.ts' import { middle, maxTwinSum } from './route.ts' test('odd length has one middle', () => { assert.equal(middle(fromArray([11, 12, 13, 14, 15]))?.val, 13) }) test('even length takes the second middle', () => { assert.equal(middle(fromArray([11, 12, 13, 14]))?.val, 13) }) test('one stop and no stops', () => { assert.equal(middle(fromArray([7]))?.val, 7) assert.equal(middle(null), null) }) test('twin sums pair mirrored stops', () => { assert.equal(maxTwinSum(fromArray([3, 8, 1, 6])), 9) assert.equal(maxTwinSum(fromArray([7, 1, 4, 9, 2, 5])), 13) })
✔ odd length has one middle (0.5464ms) ✔ even length takes the second middle (0.0951ms) ✔ one stop and no stops (0.092ms) ✔ twin sums pair mirrored stops (0.102ms) ℹ tests 4 ℹ pass 4 ℹ fail 0
One test run on this machine; the times vary
The twin-sum function leaves the second half reversed, which changes the list. A caller who still needs the original order should reverse it back, as the palindrome lesson in this chapter does. The route [3, 8, 1, 6] has twin sums 3 + 6 and 8 + 1, both 9. The route [7, 1, 4, 9, 2, 5] has twin sums 12, 3 and 13, so the largest is 13.
Both functions run in O(n) time and use O(1) extra space. Related on LeetCode: Middle of the Linked List is the first function, and Maximum Twin Sum of a Linked List is the second.
For a list of six nodes, which node does each version return?
- middle returns the fourth node, the second of the two middles. firstMiddle returns the third.
Why reverse the second half for the twin sums?
- A list cannot be walked backwards. Reversing the half lets two forward walks pair each node with its mirror.
What does the twin-sum function leave behind?
- The second half stays reversed. Reverse it again if the caller needs the original list.
Part 4 · A coupon code that settles at 1
A sequence with no list in sight
Two speeds work on any sequence where each value determines the next, not only on linked lists. A promotion system draws coupon codes by this rule: replace a number by the sum of the squares of its digits, and repeat. Some codes settle at 1 and are valid. The others never do, and the system must detect that and stop instead of looping.
For 7 the sequence is 7, 49, 97, 130, 10, 1, and it stays at 1 because 1 squared is 1. For 4 it goes 4, 16, 37, 58, 89, 145, 42, 20, then back to 4 and round again. Every number has exactly one next number, so the sequence is an implicit linked list, where "next" is a function call instead of a stored pointer. It either reaches 1 or enters a cycle.
There is a second reason this must terminate. A number with d digits has a digit-square sum of at most d times 81, which is much smaller than the number once it has four or more digits. So the values stay bounded, and a bounded sequence of deterministic steps must repeat a value or reach 1.
The two ways to detect it
The direct method stores every value seen in a Set and stops when a value repeats or reaches 1. The two-speed method keeps only two numbers: slow takes one step, fast takes two, and the loop stops when they are equal or when fast reaches 1.
// Replace a number by the sum of the squares of its digits. export function step(n: number): number { let sum = 0 for (; n > 0; n = Math.floor(n / 10)) sum += (n % 10) ** 2 return sum } // Two speeds, no set: true when the sequence reaches 1. export function settlesAtOne(n: number): boolean { let slow = n let fast = step(n) while (fast !== 1 && slow !== fast) { slow = step(slow) fast = step(step(fast)) } return fast === 1 } // The same answer by remembering every value seen. export function settlesWithSet( n: number, ): { ok: boolean; kept: number } { const seen = new Set<number>() while (n !== 1 && !seen.has(n)) { seen.add(n) n = step(n) } return { ok: n === 1, kept: seen.size } }
Notice the loop condition. It stops when fast hits 1, because from 1 the sequence stays at 1 and the pointers would meet there anyway. Checking fast === 1 first gives the right answer without waiting for the pointers to coincide.
import test from 'node:test' import assert from 'node:assert/strict' import { step, settlesAtOne } from './coupons.ts' test('digit squares', () => { assert.equal(step(7), 49) assert.equal(step(130), 10) }) test('known settling and looping codes', () => { assert.equal(settlesAtOne(1), true) assert.equal(settlesAtOne(7), true) assert.equal(settlesAtOne(20), false) assert.equal(settlesAtOne(4), false) })
✔ digit squares (0.8489ms) ✔ known settling and looping codes (0.1904ms) ℹ tests 2 ℹ pass 2 ℹ fail 0
One test run on this machine; the times vary
Comparing the two on 1 lakh numbers
The run below prints the two example sequences and then checks every number from 1 to 1,00,000 with both methods. It also counts how many values the set version stored at most, and for each number that never settles, whether its sequence passes through 4.
import { step, settlesAtOne, settlesWithSet } from './coupons.ts' for (const start of [7, 4]) { const path = [start] while (path.length < 12 && path.at(-1) !== 1) { path.push(step(path.at(-1)!)) } console.log(`${start}: ${path.join(' -> ')}`) } let disagree = 0 let happy = 0 let mostKept = 0 let through4 = 0 let stuck = 0 for (let n = 1; n <= 100_000; n++) { const a = settlesAtOne(n) const b = settlesWithSet(n) if (a !== b.ok) disagree++ if (a) happy++ mostKept = Math.max(mostKept, b.kept) if (!a) { stuck++ let x = n for (let k = 0; k < 100 && x !== 4; k++) x = step(x) if (x === 4) through4++ } } console.log(`up to 100000: ${happy} settle at 1, ${disagree} differ`) console.log(`largest set: ${mostKept} values; two pointers hold 2`) console.log(`${through4} of ${stuck} that never settle reach 4`)
7: 7 -> 49 -> 97 -> 130 -> 10 -> 1 4: 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 up to 100000: 14377 settle at 1, 0 differ largest set: 20 values; two pointers hold 2 85623 of 85623 that never settle reach 4
Both methods agree on every number; the set holds at most 20 values
The two methods agree on all 1,00,000 numbers, with 14,377 settling at 1. The set never held more than 20 values here, while the two-pointer version holds two. For these small sequences the saving is not worth much, but the idea is what matters: when a sequence is expensive to store or very long, two speeds need no storage at all.
The last line is a fact found by running: every one of the 85,623 numbers up to 1,00,000 that never settled passed through 4. That matches the cycle seen for 4, which has eight values. The bound from the first page turns it into a proof for every number. A start with four or more digits has a smaller next value, so every sequence falls below 1,000, and a number below 1,000 has a next value of at most 243, so it stays there. Every start below 1,000 was in the run, so every sequence either reaches 1 or joins the cycle through 4. For other rules, do not assume a single cycle without a check like this one.
Related on LeetCode: Happy Number is this problem.
Part 5 · One repeated ticket number
An array as a hidden list
A raffle issues n + 1 tickets numbered from 1 to n, so at least one number is issued twice. The task is to find a repeated number, without changing the array and with O(1) extra space. A set would take O(n) space and sorting would change the array or copy it.
The pigeonhole principle explains why a repeat must exist: n + 1 items placed in n possible values cannot all be different. Now treat the array as a list. Read nums[i] as "the node after i". Every value is between 1 and n, so every index you jump to is a valid index, and no jump goes to index 0, because 0 is never a value. Index 0 is therefore a node that nothing points to, which makes a good starting point outside any cycle.
A repeated value means that two different indices hold the same number, so two different nodes point to the same next node. The path that starts at index 0 must run into a cycle, because the indices are finite. The node where it joins the cycle has two incoming links, one from the path and one from the cycle, so its index is the repeated number.
Watching the jumps
Both start at index 0: s jumps once, f jumps twice
Read it as steps
Two pointers jump through the array until they meet and then find the entry
After the pointers meet, restarting one at index 0 and stepping both one at a time brings them to the same index, and that index is the repeated ticket, 3. Index 3 is the node reached from both index 0 and index 5, which both hold the value 3.
The code and a stress test
// n + 1 ticket numbers, each from 1 to n, so one repeats. // Treat nums[i] as "the next index after i" and find the loop. export function repeatedTicket(nums: number[]): number { let slow = nums[0] let fast = nums[nums[0]] while (slow !== fast) { slow = nums[slow] fast = nums[nums[fast]] } // slow and fast met inside the loop; find where the loop begins let a = 0 while (a !== slow) { a = nums[a] slow = nums[slow] } return a }
import test from 'node:test' import assert from 'node:assert/strict' import { repeatedTicket } from './tickets.ts' test('finds the repeated ticket', () => { assert.equal(repeatedTicket([3, 6, 2, 1, 5, 3, 7, 4]), 3) }) test('smallest input', () => { assert.equal(repeatedTicket([1, 1]), 1) }) test('a repeat that appears three times', () => { assert.equal(repeatedTicket([4, 2, 4, 3, 4]), 4) }) test('does not change the array', () => { const nums = [4, 1, 3, 2, 4] repeatedTicket(nums) assert.deepEqual(nums, [4, 1, 3, 2, 4]) })
✔ finds the repeated ticket (0.5602ms) ✔ smallest input (0.0902ms) ✔ a repeat that appears three times (0.081ms) ✔ does not change the array (0.5052ms) ℹ tests 4 ℹ pass 4 ℹ fail 0
One test run on this machine; the times vary
For a reference answer, a counting version marks each value as it is seen and returns the first one that is seen twice.
export function repeatedByCount(nums: number[]): number { const seen = new Array<boolean>(nums.length).fill(false) for (const x of nums) { if (seen[x]) return x seen[x] = true } return -1 }
import { mulberry32 } from './rng.ts' import { repeatedTicket, repeatedByCount } from './tickets.ts' console.log(repeatedTicket([3, 6, 2, 1, 5, 3, 7, 4])) const rand = mulberry32(5) for (let round = 1; round <= 3000; round++) { const n = 1 + Math.floor(rand() * 12) // a shuffled 1..n plus one extra copy of a random value const nums = Array.from({ length: n }, (_, i) => i + 1) nums.push(1 + Math.floor(rand() * n)) for (let i = nums.length - 1; i > 0; i--) { const j = Math.floor(rand() * (i + 1)) ;[nums[i], nums[j]] = [nums[j], nums[i]] } const copy = nums.slice() if (repeatedTicket(nums) !== repeatedByCount(nums)) { console.log('mismatch', copy) process.exit(1) } if (nums.join() !== copy.join()) { console.log('array was changed', copy) process.exit(1) } } console.log('3000 random lists agree; the array was never changed')
3 3000 random lists agree; the array was never changed
The first line is the ticket from the scene; the second is the stress result
Two shortcuts that look like O(1) space break the rules. Marking each seen value by making nums[x] negative finds the repeat, but changes the array. Subtracting 1 + 2 + ... + n from the total finds the repeat only when it appears exactly twice: for 4 1 3 2 4 it gives 4, but for 2 2 2 2 2 it gives 0.
Part 6 · Is the token list a palindrome
Combining three small techniques
A system keeps session tokens in a linked list and a checker wants to know whether the list reads the same forwards and backwards. An array could be compared from both ends, but a list can only be walked forwards. Copying the values into an array works in O(n) space. The in-place approach needs O(1) and combines the tools from this chapter.
- Find the middle with fast and slow pointers.
- Reverse the second half in place.
- Walk the first half and the reversed half together, comparing values.
- Reverse the second half again so the list is as it was.
The last step is easy to forget. A function that answers a yes-or-no question should not leave the caller's list damaged. Code that runs later may walk the same list.
The code
function reverse(head: ListNode | null): ListNode | null { let prev: ListNode | null = null while (head) { const next: ListNode | null = head.next head.next = prev prev = head head = next } return prev }
// Is the token list a palindrome? Leaves the list as it found it. export function isPalindromeList(head: ListNode | null): boolean { let slow = head let fast = head while (fast && fast.next) { slow = (slow as ListNode).next fast = fast.next.next } const back = reverse(slow) // second half, reversed let ok = true let a = head as ListNode for (let b = back; b; b = b.next) { if (a.val !== b.val) { ok = false; break } a = a.next as ListNode } reverse(back) // restore the second half return ok }
After the first loop, slow is on the middle node: for an odd count, the exact middle, and for an even count, the first node of the second half. Reversing from slow gives a list that starts at the last node. When the count is odd the middle node ends up as the last node of the reversed half, so the comparison loop, which runs while the reversed half has nodes, compares it with itself. That does no harm.
The loop stops at the first mismatch, but reverse is still called on the way out so the list is restored either way. A break is used rather than a return for that reason.
Tests that check the list afterwards
import test from 'node:test' import assert from 'node:assert/strict' import { fromArray, toArray } from './list.ts' import { isPalindromeList } from './tokens.ts' test('even and odd palindromes', () => { assert.equal(isPalindromeList(fromArray([6, 3, 3, 6])), true) assert.equal(isPalindromeList(fromArray([6, 3, 9, 3, 6])), true) }) test('not palindromes', () => { assert.equal(isPalindromeList(fromArray([6, 3, 9, 6])), false) assert.equal(isPalindromeList(fromArray([6, 3])), false) }) test('empty and single lists', () => { assert.equal(isPalindromeList(null), true) assert.equal(isPalindromeList(fromArray([5])), true) }) test('the list is unchanged afterwards', () => { const xs = [4, 8, 15, 8, 4, 9] const head = fromArray(xs) isPalindromeList(head) assert.deepEqual(toArray(head), xs) })
✔ even and odd palindromes (0.6354ms) ✔ not palindromes (0.1048ms) ✔ empty and single lists (0.0769ms) ✔ the list is unchanged afterwards (0.5376ms) ℹ tests 4 ℹ pass 4 ℹ fail 0
One test run on this machine; the times vary
The last test is the important one: it converts the list to an array after the call and compares it with the original values. The first half is never changed, and the second half is reversed twice, so the whole list comes back as it was.
Why not compare with a stack? Push the first half while walking, then pop while comparing the second half. It is just as simple and takes O(n) space. The reversal trades a little complexity for O(1) space, and it is the same reversal the in-place linked list chapter uses for reordering. Know both: the stack version is quicker to write correctly, and the reversal is the one to use when memory is tight or the list is long.
The time is O(n): one pass to find the middle, one to reverse, one to compare and one to restore. The space is O(1). Related on LeetCode: Palindrome Linked List is this problem.
| Term | Meaning |
|---|---|
| Linked list | A chain of nodes, each holding a value and a reference to the next |
| Cycle |
All chapters · Previous: Two Pointers: Pairs, Partitions and In-Place Scans