Tools for linked‑list cycle detection, middle‑node finding, and removing duplicates.
Detect cycles in linked structures using Floyd’s algorithm
Fast moves 2×, slow 1× to find midpoint
Slow pointer marks end of cleaned list, fast scans ahead
Any problem with “gap” or spacing in lists
O(n), two pointers traverse at different speeds
O(1) extra space — no new structures
Not advancing fast pointer twice or handling null checks
Always check `fast && fast.next` in the loop condition
Detect cycle in linked list using fast/slow pointers
function hasCycle(head: ListNode | null): boolean {
let slow = head, fast = head
while (fast && fast.next) {
slow = slow.next!
fast = fast.next.next!
if (slow === fast) return true
}
return false
}Fast pointer moves 2x, slow moves 1x to find middle
function middleNode(head: ListNode | null): ListNode | null {
let slow = head, fast = head
while (fast && fast.next) {
slow = slow!.next!
fast = fast.next.next
}
return slow
}Use slow pointer to build unique portion, fast to scan ahead
function deleteDuplicates(head: ListNode | null): ListNode | null {
let dummy = new ListNode(0), tail = dummy
let curr = head
while (curr) {
if (!tail.next || tail.next.val !== curr.val) {
tail.next = curr
tail = tail.next
}
curr = curr.next
}
tail.next = null
return dummy.next
}String Compression
medium