Leetcode Problem 142. Linked List Cycle II

142. Linked List Cycle II

Leetcode Solutions

Floyd's Tortoise and Hare Algorithm

  1. Initialize two pointers, tortoise and hare, to the head of the linked list.
  2. Move tortoise one step and hare two steps at a time until they either meet or hare reaches the end of the list.
  3. If hare reaches the end (i.e., hare or hare.next is null), return null as there is no cycle.
  4. If tortoise and hare meet, reset hare to the head of the list.
  5. Move both tortoise and hare one step at a time until they meet again.
  6. The node where they meet is the entrance to the cycle. Return this node.
UML Thumbnail

Hash Set Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...