Bird
Raised Fist0
DSA Pythonprogramming~30 mins

Detect if a Linked List is Circular in DSA Python - Build from Scratch

Choose your learning style10 modes available
Detect if a Linked List is Circular
📖 Scenario: Imagine you have a chain of connected train cars. Sometimes, the last car connects back to an earlier car, making a loop. We want to check if the train cars form such a loop or if the chain ends normally.
🎯 Goal: You will build a simple linked list and write code to check if it forms a circular loop or not.
📋 What You'll Learn
Create a linked list with exactly 4 nodes with values 10, 20, 30, and 40
Add a variable called head pointing to the first node
Write a function called is_circular that takes head and returns True if the list is circular, else False
Test the function on a circular linked list where the last node points back to the second node
Print the result of the circular check
💡 Why This Matters
🌍 Real World
Circular linked lists are used in real-world applications like music playlists that repeat, or in operating systems for task scheduling where the tasks cycle continuously.
💼 Career
Understanding how to detect cycles in linked lists is important for software developers working with data structures, debugging memory leaks, or designing efficient algorithms.
Progress0 / 4 steps
1
Create the linked list nodes and connect them
Create a class called Node with attributes data and next. Then create 4 nodes with values 10, 20, 30, and 40. Connect them in order so that each node's next points to the next node. Finally, create a variable called head that points to the first node.
DSA Python
Hint

Remember, each node should have a data value and a next pointer. Connect nodes by setting node1.next = node2, and so on.

2
Make the linked list circular by connecting last node to second node
Modify the linked list so that the last node (node4) points back to the second node (node2), creating a loop.
DSA Python
Hint

Set node4.next = node2 to create the circular link.

3
Write a function to detect if the linked list is circular
Write a function called is_circular that takes the head of the linked list as input. Use two pointers called slow and fast. Move slow by one step and fast by two steps in a loop. If fast or fast.next becomes None, return False. If slow and fast meet, return True.
DSA Python
Hint

Use the 'slow and fast pointer' method to detect loops. Move slow by one and fast by two steps. If they meet, the list is circular.

4
Print the result of the circular linked list check
Call the function is_circular with head and print the result.
DSA Python
Hint

Use print(is_circular(head)) to show if the list is circular.

Practice

(1/5)
1. What does it mean if a linked list is circular?
easy
A. The linked list nodes are sorted in ascending order
B. The linked list has no nodes
C. The linked list has only one node
D. The last node points back to one of the previous nodes, forming a loop

Solution

  1. Step 1: Understand linked list structure

    A linked list is a chain of nodes where each node points to the next node.
  2. Step 2: Define circular linked list

    If the last node points back to any previous node, it creates a loop, making the list circular.
  3. Final Answer:

    The last node points back to one of the previous nodes, forming a loop -> Option D
  4. Quick Check:

    Circular linked list means loop exists [OK]
Hint: Circular means last node links back inside list [OK]
Common Mistakes:
  • Thinking circular means sorted
  • Confusing empty list with circular
  • Assuming single node list is always circular
2. Which of the following Python code snippets correctly checks if a linked list is circular?
easy
A. 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
B. def is_circular(head): current = head while current: current = current.next return True
C. def is_circular(head): return head.next == None
D. def is_circular(head): return head == None

Solution

  1. Step 1: Understand Floyd's cycle detection

    Using two pointers (slow and fast) moving at different speeds detects loops if they meet.
  2. 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.
  3. Final Answer:

    Code using slow and fast pointers to detect loop -> Option A
  4. Quick 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]
Hint: Use two pointers moving at different speeds [OK]
Common Mistakes:
  • Not checking fast pointer's next before accessing
  • Assuming reaching None means circular
  • Returning True without loop detection
3. What will be the output of the following code snippet?
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))
medium
A. True
B. False
C. None
D. Runtime Error

Solution

  1. Step 1: Understand list structure

    Nodes 1->2->3, and third points back to head, making a loop.
  2. Step 2: Trace Floyd's cycle detection

    Slow and fast pointers will eventually meet inside the loop, so function returns True.
  3. Final Answer:

    True -> Option A
  4. Quick Check:

    Loop detected = True [OK]
Hint: Loop means slow and fast pointers meet [OK]
Common Mistakes:
  • Ignoring the loop created by third.next = head
  • Assuming function returns False by default
  • Confusing None return with False
4. Find the error in the following code that tries to detect if a linked list is circular:
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 False
medium
A. The function should return True outside the loop unconditionally
B. The slow pointer should move two steps instead of one
C. The while loop condition should check if fast and fast.next exist
D. The fast pointer should start at head.next

Solution

  1. Step 1: Analyze while loop condition

    Current condition checks fast.next and fast.next.next but does not check if fast itself is None.
  2. Step 2: Correct condition to avoid runtime error

    Should check if fast and fast.next exist before accessing fast.next.next to prevent errors.
  3. Final Answer:

    The while loop condition should check if fast and fast.next exist -> Option C
  4. Quick Check:

    Check fast and fast.next to avoid errors [OK]
Hint: Always check pointer exists before accessing next [OK]
Common Mistakes:
  • Not checking if fast is None before fast.next
  • Moving slow pointer incorrectly
  • Returning True too early
5. You have a linked list where the last node points to the third node, making it circular. How would you modify the detection function to also return the node where the loop starts?
hard
A. Return the node where slow and fast first meet during detection
B. Use Floyd's algorithm: after detecting loop, reset slow to head and move slow and fast one step until they meet; that node is loop start
C. Return the head node always as loop start
D. Use a hash set to store visited nodes and return the first repeated node

Solution

  1. Step 1: Detect loop using Floyd's cycle detection

    Use slow and fast pointers to find if loop exists by meeting inside the loop.
  2. 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.
  3. Final Answer:

    Use Floyd's algorithm with reset slow pointer to find loop start -> Option B
  4. Quick Check:

    Reset slow and move both pointers to find loop start [OK]
Hint: After loop detection, reset slow to head and move both one step [OK]
Common Mistakes:
  • Returning meeting point as loop start without reset
  • Always returning head as loop start
  • Not handling loop detection before finding start
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard