DSA AnimatorREVISION VIDEOS
← Back to problems
New

Linked List Cycle II — LeetCode 142 video explanation

If the list has a cycle, return the node where the cycle begins. Otherwise return null, using O of 1 extra space.

Loading videos…

DSA Animator › DSA Revision › Linked List › Linked List Cycle II

Key moments in the Linked List Cycle II video

0:04Problem0:12Example0:18Brute force0:25Key idea0:36Dry run0:51Code1:05Takeaway

What you will learn

Remember: the head and the meeting point are the same distance from the entry. Meet, reset one pointer, then walk together. The video solves Linked List Cycle II (LeetCode 142, Medium) with the Fast & Slow Pointers pattern from the Linked List topic, and you can replay every step in the interactive Linked List Cycle II animation.

Linked List Cycle II video transcript

Problem

If the list has a cycle, return the node where the cycle begins. Otherwise return null, using O of 1 extra space.

Example

For 3, 2, 0, minus 4, where the last node points back to 2, the cycle starts at 2.

Brute force

A hash set returns the first node seen twice, but uses O of n space. Floyd's algorithm can find the entry too.

Key idea

First, run slow and fast until they meet inside the cycle. Then move one pointer back to the head. Move both one step at a time, and they meet exactly at the cycle entry.

Dry run

As in problem 141, slow and fast meet at minus 4. Put one pointer back at the head, 3. Step both once: the head pointer moves to 2, and the other goes from minus 4 to 2. They meet at 2, which is the entry of the cycle.

Code

In code, the first loop is the cycle check from problem 141. After they meet, set a pointer to head. Move both one step until they are equal, and return that node, so it's O of n time and O of 1 space.

Takeaway

Remember: the head and the meeting point are the same distance from the entry. Meet, reset one pointer, then walk together.

More Linked List revision videos

← All 185 DSA revision videos