Unit 6 Session 2 (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
HAPPY CASE
Input: A list where the last node points back to the first node (e.g., num1 -> num2 -> num3 -> num1)
Output: True
Explanation: The tail node points back to the head, forming a circular linked list.
EDGE CASE
Input: A single node that does not point to itself (e.g., num1)
Output: False
Explanation: The single node points to None, indicating it is not a circular linked list.
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
For Circular Linked List detection problems, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Start at the head and traverse the list, checking if the tail points back to the head.
1) Start at the head.
2) If the list is empty, return False.
3) Traverse through the list. If any node points back to the head, return True.
4) If the end of the list is reached (i.e., current.next is None), return False.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
def is_circular(head):
if not head:
return False # An empty list is not circular by definition
current = head
while current.next:
current = current.next
if current.next == head:
return True # Found that tail points back to head
return False
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
O(n)
where n
is the number of nodes in the linked list. The entire list is traversed in the worst case.O(1)
as no extra space is used other than a few variables for tracking nodes.