Find Length of Loop
Problem Statement
You are given head, the first node of a singly linked list. The list may contain a loop: the tail's next may point back to some earlier node.
If there is a loop, return how many nodes are in it. If there is no loop, return 0.
Write int countNodesInLoop(ListNode* head). GFG calls its node type Node (with data and next); here we use LeetCode's ListNode (val, next) — the logic is identical.
c in the examples is only used to build the test list: the tail links to the c-th node (1-based), and c = 0 means no loop. Your function does not receive it.
head — the first node of the list.
The number of nodes in the loop, or 0 if there is no loop.
The tail (45) links to the 4th node (33). The loop is 33 → 10 → 21 → 39 → 90 → 58 → 45 → 33, which has 7 nodes.
There is no loop.
The tail links back to the head, so all 4 nodes are in the loop.
- • 1 ≤ number of nodes ≤ 10^5
- • 1 ≤ node value ≤ 10^4
- • 0 ≤ c ≤ number of nodes
- • Expected: O(N) time, O(1) extra space
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Map node → step index; length = current step − first step
Find a node inside the loop with slow/fast, then count one lap from it
Walk the list counting steps, and store each node's pointer with the step at which we first reached it. The first time we reach a node that is already in the map, we have just finished one lap of the loop, so the loop length is step − firstStep[node]. If we reach null, there is no loop.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Linked List — Fast & Slow translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.