Leetcode 142. Linked List Cycle II

Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.
  • The number of the nodes in the list is in the range [0, 104].
  • -105 <= Node.val <= 105
  • pos is -1 or a valid index in the linked-list.
  1. if you just want to check the ListNode had cycle, we can use two pointer, one move faster, another move slower. If they meet, it means the ListNode had a cycle.
  2. We want to know where they first meet. If we could track every position we have been to, we can have the answer.
  3. Trick part is we can start a new ListNode from the head, and move the slow pointer and new pointer together. The place they meet will be the answer.
  4. below photo from wmhlailenow help me understand the trick.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gary Chiang

Gary Chiang

CS new grad, 6 years experience related to supply chain management. Located in Bay area