Linked List Cycle II
Master this topic with zero to advance depth.
Linked List Cycle II
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
Visual Representation
3 -> 2 -> 0 -> -4
^ |
+----------+
Cycle starts at node with value 2.Examples
Level I: HashSet
Intuition
Store visited nodes in a set. The first node we encounter that is already in the set is the start of the cycle.
Level II: Node Marking (Magic Value)
Intuition
If we can modify the node values, we can mark each visited node with a special value (outside the problem's constraints). If we encounter a node already marked with that value, it's the start of the cycle.
Detailed Dry Run
List: 3 -> 2 -> 0 -> -4 (back to 2).
- 3.val = 100001.
- 2.val = 100001.
- 0.val = 100001.
- -4.val = 100001.
- Next is 2, whose val is 100001. Cycle start found.
⚠️ Common Pitfalls & Tips
This modifies the original list. In many real-world or interview scenarios, modifying the input data is not allowed unless specified.
Level III: Floyd's Cycle-Finding Algorithm
Intuition
Detect cycle first, then reset one pointer to head and move both at speed 1 to find meeting point.
Visual Trace
D = Distance to cycle, S = Meeting point from start, C = Cycle length.
Moving D steps from head and D steps from meeting point hits cycle start.Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.