TIP102 Unit 6 Session 2 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: marker1 = Node("Marker 1")
marker2 = Node("Marker 2")
marker3 = Node("Marker 3")
marker1.next = marker2
marker2.next = marker3
marker3.next = marker1
Output: 3
Explanation: The linked list has a loop with three markers.
EDGE CASE
Input: marker1 = Node("Marker 1")
marker1.next = marker1 # Single node loop
Output: 1
Explanation: The linked list has a loop with one marker.
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 Length Calculation, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: We will traverse the linked list starting from the head and count the nodes until we return to the head, which indicates that we've completed the loop.
1) Initialize a variable `length` to 1 to count the nodes.
2) Initialize a pointer `current` to the head of the list.
3) Traverse the list:
a) Move the `current` pointer to the next node.
b) Increment `length` by 1.
c) If `current` points back to the head, stop the traversal.
4) Return the value of `length`.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def trail_length(trailhead):
if not trailhead:
return 0
current = trailhead
length = 1
while current.next != trailhead:
current = current.next
length += 1
return length
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
marker1
, marker2
, and marker3
linked list to verify that the function correctly calculates the length of the loop.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 exactly once until the loop is detected.O(1)
because the algorithm uses a constant amount of extra space for pointers and counters.