
Problem
Solution
Submissions
If LinkedList Has Cycle
Certification: Basic Level
Accuracy: 71.43%
Submissions: 7
Points: 5
Write a Java program to determine if a linked list has a cycle in it. A cycle occurs when a node in a linked list points to a previous node, creating a loop. 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:
- Tail node connects to the node at index 1 → cycle exists
Example 2
- Input: head = [1,2], pos = 0
- Output: true
- Explanation:
- Tail node connects to the node at index 0 → cycle exists
Constraints
- 0 ≤ number of nodes ≤ 10^4
- -10^5 ≤ Node.val ≤ 10^5
- 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 Floyd's Cycle-Finding Algorithm (Tortoise and Hare).
- Use two pointers moving at different speeds.
- If there's a cycle, the fast pointer will eventually meet the slow pointer.
- If there's no cycle, the fast pointer will reach the end of the list.