Understand what the interviewer is asking for by using test cases and questions about the problem.
0
.HAPPY CASE
Input: playlist with 4 songs, where the last song points to the second song
Output: 3
Explanation: The linked list contains a cycle of length 3.
EDGE CASE
Input: playlist = None
Output: 0
Explanation: An empty list does not contain a cycle.
EDGE CASE
Input: playlist with 3 songs, no cycle
Output: 0
Explanation: The linked list does not contain a cycle.
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 Linked List problems involving Cycle Detection and Measurement, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: We will first use two pointers to detect the cycle. Once a cycle is detected, we will keep one pointer fixed and move the other pointer to count the length of the cycle.
1) Initialize two pointers, `slow` and `fast`, both pointing to the `head` of the list.
2) Traverse the list:
a) Move the `slow` pointer by one step.
b) Move the `fast` pointer by two steps.
c) If the slow pointer and fast pointer meet, a cycle exists.
3) If a cycle is detected:
a) Keep one pointer fixed at the meeting point.
b) Move the other pointer step by step until it meets the fixed pointer again, counting the number of steps.
4) Return the count as the length of the cycle.
5) If no cycle is detected, return `0`.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
class SongNode:
def __init__(self, song, artist, next=None):
self.song = song
self.artist = artist
self.next = next
# Function to detect the length of the cycle
def loop_length(playlist_head):
if not playlist_head:
return 0
slow = playlist_head
fast = playlist_head
# First, detect if a cycle exists
while fast and fast.next:
slow = slow.next # Move slow pointer by 1 step
fast = fast.next.next # Move fast pointer by 2 steps
# Cycle detected
if slow == fast:
# Now calculate the cycle length
cycle_length = 0
current = slow
while True:
current = current.next
cycle_length += 1
if current == slow:
break
return cycle_length
# No cycle found
return 0
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
loop_length
returns 3
.Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume N
represents the number of nodes in the linked list.
O(N)
because each node is visited at most twice, once to detect the cycle and once to measure it.O(1)
because only a constant amount of extra space is used for the pointers.