v9.1.1
Menu

Linked List Cycle

easyFREELinked ListBlind 75

Given a list of values and an integer pos indicating where the tail connects to (0-indexed), determine if the linked list has a cycle.

pos is -1 if there is no cycle. Output True if there is a cycle, False otherwise.

Example

Input
3,2,0,-4
1
Output
True
Reasoning
  • The first input line is the node values in order, so the list is 3→2→0→−43 \to 2 \to 0 \to -4 (nodes at indices 0, 1, 2, 3).
  • The second line is pos = 1: the tail node (−4-4, index 3) does not end the list but links back to the node at index 1, whose value is 22.
  • Walking the links from the head visits 3,2,0,−4,2,0,−4,2,…3, 2, 0, -4, 2, 0, -4, 2, \dots: after the first node, the three nodes 2,0,−42, 0, -4 repeat forever and the walk never reaches an end.
  • A walk that never ends is exactly what a cycle means, so the output is True.
  • Notice the loop holds the nodes from index 1 up to the tail at index 3, which is 4−1=34 - 1 = 3 nodes, and the node with value 22 is the first one the walk sees twice, right after the tail −4-4. If the tail linked to nothing, the walk would simply stop after the 4th node (−4-4).

Constraints

  • 0 <= number of nodes <= 10^4
  • -10^5 <= Node.val <= 10^5
  • pos is -1 or a valid index

More from Blind 75

solution.py

Test results

Sign in to run your code against the test cases.