Length of the Cycle
Return how many nodes are inside the cycle, counting the nodes you keep visiting once you are caught in it. If the list has no cycle, return 0. In the tests the last node points back to the node at index pos, or to nothing when pos is -1; pos itself is not passed to your method. The list is passed in as head.
Linked lists appear in the tests as the list of their values, like [1,2,3]. Each node is a ListNode with .val and .next; the class is already defined for you.
Example 1
head [3,2,0,-4]
returns 3
Nodes 2, 0, -4 form the loop.
Example 2
head [1,2,3]
returns 0
No cycle.
Constraints
0 <= number of nodes <= 50-1 <= pos < number of nodes-100 <= Node.val <= 100
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Linked lists problems
- Maximum Twin SumMedium
- Move a Value to the EndMedium
- Odd Even Linked ListMedium
- Partition ListMedium
- Plus One Linked ListMedium
- Remove All Duplicated ValuesMedium
- Remove Nodes With a Larger Node AfterMedium
- Remove Nth Node From End of ListMedium