JCSU Unit 10 Problem Set 2 (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: A linked list: A -> T -> C -> G -> A (loop) Output: 4 Explanation: The loop begins at 'T' and cycles through 4 nodes: 'T -> C -> G -> A'.
EDGE CASE Input: A linked list: C -> G -> A -> T -> None (no loop) Output: 0 Explanation: No loop exists in the DNA sequence.
EDGE CASE Input: A single node pointing to itself: A -> A Output: 1 Explanation: The loop contains only one node.
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 cycle detection in linked lists, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea:
Use Floyd's Cycle Detection Algorithm to detect a loop. If a loop is detected, measure its length by traversing the loop until returning to the starting point.
slow
and fast
, both pointing to the head of the list.slow
one step and fast
two steps in each iteration.slow
meets fast
, a loop is detected. If the end of the list (None
) is reached, return 0.Implement the code to solve the algorithm.
def detect_dna_loop_length(head):
# Use Floyd's Cycle Detection algorithm
slow, fast = head, head
# Step 1: Detect if a loop exists
while fast and fast.next:
slow = slow.next # Move slow pointer one step
fast = fast.next.next # Move fast pointer two steps
if slow == fast: # Loop detected
break
else:
# If no loop is detected, return 0
return 0
# Step 2: Calculate loop length
loop_length = 1 # Initialize loop length counter
current = slow.next
while current != slow: # Traverse the loop until returning to the starting point
loop_length += 1
current = current.next
return loop_length # Return the calculated loop length
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Example 1:
Example 2:
Example 3:
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume n is the number of nodes in the linked list.