Linked List Cycle IV

curriculum-track follow-up — find the cycle entry and length; not a canonical LeetCode problem.

Medium
Time O(n) Space O(1)
4 min read
fast-slow linked-list

Problem#

(curriculum variant — no canonical LeetCode entry.) Given a possibly-cyclic singly linked list, return a pair (entry, length) where entry is the node where the cycle begins and length is the cycle’s length. Return (nullptr, 0) if there’s no cycle.

Examples#

  • [1 → 2 → 3 → 4 → 5 → 3 → …] → entry = node 3, length = 3.

Constraints#

  • Length in [0, 10^4].

Hints#

Hint 1
Phase 1 to detect, phase 2 to locate the entry, then walk one full lap to count.

Approach#

Combine Cycle and Cycle II: once you find the entry, walk forward until you return to the entry — that’s the cycle length.

Solution#

Linked List Cycle IV (entry + length)
struct ListNode {
int val;
ListNode* next;
ListNode(int v): val(v), next(nullptr) {}
};
pair<ListNode*, int> detectCycleAndLength(ListNode* head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
ListNode* entry = head;
while (entry != slow) { entry = entry->next; slow = slow->next; }
int len = 1;
for (ListNode* p = entry->next; p != entry; p = p->next) ++len;
return {entry, len};
}
}
return {nullptr, 0};
}

Editorial#

Two well-known sub-problems wired together: Cycle II for the entry, then a single forward walk for the length. Each operation is O(n) and uses O(1) memory.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.