TIP102 Unit 6 Session 1 Standard (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
HAPPY CASE
Input: playlist with 4 songs, where the last song points to the second song
Output: True
Explanation: The linked list contains a cycle.
EDGE CASE
Input: playlist = None
Output: False
Explanation: An empty list does not contain a cycle.
EDGE CASE
Input: playlist with 3 songs, no cycle
Output: False
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, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: We will use two pointers, a slow pointer and a fast pointer. The slow pointer will move one step at a time, while the fast pointer will move two steps. If there is a cycle, the fast pointer will eventually meet the slow pointer. If the fast pointer reaches the end of the list, then there is no 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 the fast pointer reaches the end of the list, return False (no cycle).
4) Return True if a cycle is detected; otherwise, return False.
⚠️ 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
def on_repeat(playlist_head):
if not playlist_head:
return False
slow = playlist_head
fast = playlist_head
while fast and fast.next:
slow = slow.next # Move slow pointer by 1 step
fast = fast.next.next # Move fast pointer by 2 steps
# If slow and fast meet, there's a cycle
if slow == fast:
return True
# If fast reaches the end, there's no cycle
return False
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
on_repeat
returns True
.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 once.O(1)
because only a constant amount of extra space is used for the pointers.