141. Linked List Cycle
#linked-list #cycle-detection
Problem
Intuition
Time Complexity
Space Complexity
Solution
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
// n -> number of nodes in linked list
// m -> Number of loop rotations (generally a very small number)
// Time Complexity: O(n), traverse through the list once
// It could be O(m * n), but the number of loop rotations could be a very small number
// Space Complexity: O(1), auxillary space, we are not allocating any extra space
// If the head is null, there is no cycle, so return false
if (head == null) {
return false;
}
// Initialize two pointers, walker and runner, both pointing to the head of the linked list
ListNode walker = head;
ListNode runner = head;
// Move the runner pointer by two steps and the walker pointer by one step
// If there is a cycle, the runner will eventually catch up with the walker
while (runner != null && runner.next != null) {
walker = walker.next;
runner = runner.next.next;
// If the walker and runner meet, there is a cycle, so return true
if (walker == runner) {
return true;
}
}
// If the loop completes without finding a cycle, return false
return false;
}
}
Last updated
Was this helpful?