Cycle Length in Linked List

Given the head of a linked list that contains a cycle, return the length of the cycle (number of nodes in the loop). If no cycle exists, return 0. Example: Input: head = [1,2,3,4,5], pos = 1 Output: 4 Explanation: Cycle through nodes [2,3,4,5] (4 nodes). Pattern focus: List Cycle Entry (detect with fast/slow, then count loop length).

Input Format

head = ListNode

Output Format

return int

Constraints

  • The number of nodes is in the range [0, 10^4].
  • -10^5 <= Node.val <= 10^5

Examples

Example 1:

Input:

head = [1,2,3,4,5]
pos = 1

Output:

4

Explanation:

Cycle of length 4 (nodes 2→3→4→5→back to 2).

Example 2:

Input:

head = [1,2,3,4,5]
pos = -1

Output:

0

Explanation:

No cycle, return 0.

Loading...
Cycle Length in Linked List - Linked List