Length 1:13Loading the video
Loading the video
Does a linked list loop back on itself? Move a slow pointer one step and a fast pointer two steps. If they ever meet there is a cycle, and no extra memory is needed.
Narrated by an AI voice.
You get the head of a linked list.
Does the list loop back on itself?
That is LeetCode problem one forty one.
Each node holds a value and a pointer to the next node.
In a normal list, the last node points to null.
In a list with a cycle, the last node points back to an earlier node.
If you walk this list one node at a time, you never reach the end.
A simple loop would run forever.
One fix is to remember every node you visit in a set.
If you see a node twice, there is a cycle.
That takes linear time, but it also uses extra memory for every node.
A better idea uses two pointers that move at different speeds.
The slow pointer moves one step.
The fast pointer moves two steps.
Think of two runners on a circular track.
The faster runner always catches up and laps the slower one.
In a list with a cycle, fast and slow must meet.
If there is no cycle, the fast pointer reaches the end first.
Then we know the list ends, and we return false.
Here is the code in JavaScript.
Both pointers start at the head.
The loop runs while fast and the node after fast exist.
Slow moves one step, and fast moves two.
If they point to the same node, we return true.
If fast falls off the end, we return false.
Here is an example.
Positions count from zero, and the last node points back to position one.
After one step, slow is on eight and fast is on five.
After two steps, slow is on five, and fast wraps around to eight.
After three steps, both sit on twelve.
They meet, so we return true.
This runs in linear time, because fast catches slow within a few trips around the loop.
It uses constant extra memory, only two pointers.
Fast and slow pointers find a cycle without remembering any nodes.
Two pointers: how it works and when to use it
Two pointers walk a list from both ends, or one behind the other, so a pair search takes one pass. Signals, a worked example, code and practice.
Type any algorithm, interview problem or system, and get your own narrated video.
3 free videos with your own AI key. An AI key is a code from an AI company, such as Anthropic or OpenAI. Your own AI account pays for the writing. See pricing
Make a video
Length 1:13
Length 2:20
Length 1:56