323. Count Nodes in a Loop (Cycle Length)

EasyLinked ListLinked ListFloyd's Cycle DetectionCycle Length

Given a linked list (which may or may not contain a cycle), return the length of the cycle if one exists, otherwise return 0.

The input specifies the list as an array plus a pos value: pos is the 0-indexed position where the tail connects back, or -1 if no cycle.

Use Floyd's algorithm to detect the meeting point, then count nodes in the loop.

Input: Array of node values and integer pos (-1 if no cycle, else 0-indexed cycle entry).

Output: Integer — number of nodes in the cycle (0 if no cycle).

Examples

Example 1
Input: [1,2,3,4,5], pos=1
Output: 4
Explanation: Cycle: 2→3→4→5→2. Count=4.
Example 2
Input: [1,2,3,4,5], pos=0
Output: 5
Explanation: Cycle: 1→2→3→4→5→1. All 5 nodes in cycle.
Example 3
Input: [1,2,3], pos=-1
Output: 0
Explanation: No cycle. Return 0.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →