← DiffPush

Count nodes in loop

Standard Bar Linked List · Medium Problems of LL O(N) · O(1)

Measuring the Roundabout's Circumference

A plant's transport chain has a suspected roundabout — a section that cycles back onto itself. Control wants the number of stations trapped inside the cycling section, not just whether it exists. The two-speed probe rig confirms the loop and parks both probes at a meeting station; one probe then walks the roundabout exactly once, counting stations until it returns to that parking spot.

Input: An array head of N node values and an integer C — the 1-based position of the node the tail connects to for the loop, or 0 when there is no loop.

Output: The number of nodes inside the loop, or 0 when the list has no loop.

Constraints

Examples

Example 1

Input: {"head":[25,14,19,33,10,21,39,90,58,45],"C":4}
Output: 7
The tail reconnects to the 4th node (33); the roundabout 33-10-21-39-90-58-45 holds seven stations.

Example 2

Input: {"head":[1,0],"C":1}
Output: 2
Both nodes sit inside the loop, so the circumference is the whole list.

Solve this in your browser →

Also on LeetCode ↗