Detect if a Linked List is Circular in DSA Python - Time & Space Complexity
We want to know how long it takes to check if a linked list loops back on itself.
How does the time needed grow as the list gets longer?
Analyze the time complexity of the following code snippet.
class Node:
def __init__(self, val):
self.val = val
self.next = None
def is_circular(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
This code uses two pointers moving at different speeds to detect a loop in the linked list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that moves two pointers through the list.
- How many times: At most, it runs once per node until pointers meet or list ends.
As the list grows, the number of steps grows roughly in a straight line with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 steps |
| 100 | Up to 100 steps |
| 1000 | Up to 1000 steps |
Pattern observation: The time grows linearly as the list gets longer.
Time Complexity: O(n)
This means the time to detect a loop grows in direct proportion to the number of nodes in the list.
[X] Wrong: "The fast pointer moves twice as fast, so the time is O(n/2), which is faster than O(n)."
[OK] Correct: We ignore constants in Big-O, so O(n/2) is still O(n). The time still grows linearly with input size.
Understanding this helps you explain how to efficiently find loops in linked lists, a common real-world problem.
"What if we used only one pointer to check for a loop by visiting nodes and marking them? How would the time complexity change?"
Practice
Solution
Step 1: Understand linked list structure
A linked list is a chain of nodes where each node points to the next node.Step 2: Define circular linked list
If the last node points back to any previous node, it creates a loop, making the list circular.Final Answer:
The last node points back to one of the previous nodes, forming a loop -> Option DQuick Check:
Circular linked list means loop exists [OK]
- Thinking circular means sorted
- Confusing empty list with circular
- Assuming single node list is always circular
Solution
Step 1: Understand Floyd's cycle detection
Using two pointers (slow and fast) moving at different speeds detects loops if they meet.Step 2: Analyze code correctness
def is_circular(head): if not head: return False slow = head fast = head.next while fast and fast.next: if slow == fast: return True slow = slow.next fast = fast.next.next return False uses slow and fast pointers correctly and returns True if they meet, else False.Final Answer:
Code using slow and fast pointers to detect loop -> Option AQuick Check:
Floyd's cycle detection = def is_circular(head): if not head: return False slow = head fast = head.next while fast and fast.next: if slow == fast: return True slow = slow.next fast = fast.next.next return False [OK]
- Not checking fast pointer's next before accessing
- Assuming reaching None means circular
- Returning True without loop detection
class Node:
def __init__(self, val):
self.val = val
self.next = None
head = Node(1)
second = Node(2)
third = Node(3)
head.next = second
second.next = third
third.next = head # Creates a circular linked list
def is_circular(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
print(is_circular(head))Solution
Step 1: Understand list structure
Nodes 1->2->3, and third points back to head, making a loop.Step 2: Trace Floyd's cycle detection
Slow and fast pointers will eventually meet inside the loop, so function returns True.Final Answer:
True -> Option AQuick Check:
Loop detected = True [OK]
- Ignoring the loop created by third.next = head
- Assuming function returns False by default
- Confusing None return with False
def is_circular(head):
slow = head
fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return FalseSolution
Step 1: Analyze while loop condition
Current condition checks fast.next and fast.next.next but does not check if fast itself is None.Step 2: Correct condition to avoid runtime error
Should check if fast and fast.next exist before accessing fast.next.next to prevent errors.Final Answer:
The while loop condition should check if fast and fast.next exist -> Option CQuick Check:
Check fast and fast.next to avoid errors [OK]
- Not checking if fast is None before fast.next
- Moving slow pointer incorrectly
- Returning True too early
Solution
Step 1: Detect loop using Floyd's cycle detection
Use slow and fast pointers to find if loop exists by meeting inside the loop.Step 2: Find loop start node
Reset slow to head, then move slow and fast one step at a time; the node where they meet is the loop start.Final Answer:
Use Floyd's algorithm with reset slow pointer to find loop start -> Option BQuick Check:
Reset slow and move both pointers to find loop start [OK]
- Returning meeting point as loop start without reset
- Always returning head as loop start
- Not handling loop detection before finding start
Ready to prove it?
Pass the test and this pattern moves unknown
