DSA · Linked List · #99
Linked List Cycle
Module 42 · difficulty 2/5·⏱ 30:00starts on first keystroke
Given the `head` of a singly linked list, determine whether the list contains a cycle. A cycle exists if some node in the list can be reached again by continuously following the `next` pointer. Implement `hasCycle(head)` that returns `true` if there is a cycle, otherwise `false`. Each node has the shape `{ val, next }`; the last node of a non-cyclic list has `next === null`.
Examples
head = [3,2,0,-4], tail connects to index 1→true— The tail node (-4) points back to the node with value 2, forming a cycle.head = [1,2], tail connects to index 0→true— The second node points back to the first.head = [1], no cycle→false— A single node whose next is null has no cycle.
Constraints
- · The number of nodes is in the range [0, 10^4].
- · -10^5 <= Node.val <= 10^5
- · The cycle, if present, is created by pointing some node's next to an earlier node (or itself).
- · Must not modify the list values.
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.