
Problem
Solution
Submissions
Detect Cycle in Linked List
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript program to determine if a linked list has a cycle in it. A cycle occurs when a node in the linked list points back to a previously visited node, creating a loop. Use Floyd's Cycle Detection Algorithm (Tortoise and Hare) to solve this efficiently.
Example 1
- Input: head = [3,2,0,-4], pos = 1
- Output: true
- Explanation:
- The linked list contains nodes with values [3,2,0,-4].
- The last node (-4) points back to the node at index 1 (value 2).
- This creates a cycle: 3 → 2 → 0 → -4 → 2 (back to index 1).
- Therefore, the linked list has a cycle.
- The linked list contains nodes with values [3,2,0,-4].
Example 2
- Input: head = [1,2], pos = -1
- Output: false
- Explanation:
- The linked list contains nodes with values [1,2].
- The pos = -1 indicates there is no cycle.
- The last node (2) points to null, ending the list.
- Therefore, the linked list does not have a cycle.
- The linked list contains nodes with values [1,2].
Constraints
- The number of nodes in the list is in the range [0, 10^4]
- -10^5 <= Node.val <= 10^5
- pos is -1 or a valid index in the linked-list
- Time Complexity: O(n)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use two pointers: a slow pointer (tortoise) and a fast pointer (hare)
- Move the slow pointer one step at a time and the fast pointer two steps at a time
- If there's no cycle, the fast pointer will reach the end (null) first
- If there's a cycle, the fast pointer will eventually meet the slow pointer
- Continue the loop until either the fast pointer reaches null or both pointers meet