Typorithm · easy

Linked List Cycle

linked-list-cyclelinked-listsfloydfast-slowmeeting
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Linked List Cycle

0%

Linked Lists

Floyd's tortoise and hare: if a fast pointer ever meets the slow one, the list has a cycle.

A cycle means some node's next eventually points back into the list.

Moving fast twice as quickly, the gap to slow shrinks by one each step, so they meet inside any loop.

If fast reaches null, the list ends and there is no cycle.

01

Two speeds from the head.

02

Meeting means a cycle.

03

fast hitting null means none.

function hasCycle(head) {
  let slow = head;
  let fast = head;

  while (fast !== null && fast.next !== null) {
    slow = slow.next;
    fast = fast.next.next;

    if (slow === fast) {
      return true;
    }
  }

  return false;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Both at head

Floyd's tortoise and hare start together.

let slow = head;
  let fast = head

2. Hare runs

fast advances two nodes per slow's one.

fast = fast.next.next

3. They meet

Inside a loop, fast laps slow and they coincide.

if (slow === fast)

4. No cycle

If fast reaches null, the list terminates with no loop.

return false

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Linked List Cycle: Lesson & Practice · Typorithm | ApplyDjinn