
Problem
Solution
Submissions
Linked List Cycle Detection
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a C program to detect if a linked list has a cycle in it. A cycle in a linked list occurs when a node's next pointer points to a node that was previously visited in the list, creating a loop. The program should return true if there is a cycle in the linked list, otherwise, return false.
Example 1
- Input: head = [3,2,0,-4], pos = 1
- Output: true
- Explanation:
- Step 1: The linked list has nodes with values 3, 2, 0, and -4.
- Step 2: The last node points back to the second node (position 1).
- Step 3: This creates a cycle in the linked list.
- Step 4: Therefore, the output is true.
Example 2
- Input: head = [1,2], pos = 0
- Output: true
- Explanation:
- Step 1: The linked list has nodes with values 1 and 2.
- Step 2: The last node points back to the first node (position 0).
- Step 3: This creates a cycle in the linked list.
- Step 4: Therefore, the output is true.
Example 3
- Input: head = [1], pos = -1
- Output: false
- Explanation:
- Step 1: The linked list has only one node with value 1.
- Step 2: There is no next node, so no cycle can exist.
- Step 3: Therefore, the output is false.
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) where n is the number of nodes in the linked list
- 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
- A naive approach would be to use a hash set to track visited nodes, but that would require O(n) space
- Consider using the "tortoise and hare" algorithm (Floyd's Cycle-Finding Algorithm)
- Use two pointers that traverse the list at different speeds
- If there is a cycle, the faster pointer will eventually catch up to the slower one
- If there's no cycle, the faster pointer will reach the end of the list