TIP102 Unit 6 Session 1 Advanced (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
m
and n
.HAPPY CASE
Input: dna_strand = Node(1, Node(2, Node(3, Node(4, Node(5, Node(6, Node(7, Node(8, Node(9, Node(10)))))))))), m = 2, n = 3
Output: 1 -> 2 -> 6 -> 7 -> 11
Explanation: After retaining 2 nodes and deleting 3, the modified linked list is obtained.
EDGE CASE
Input: dna_strand = None, m = 2, n = 3
Output: None
Explanation: An empty linked list should return None.
EDGE CASE
Input: dna_strand = Node(1), m = 1, n = 1
Output: 1
Explanation: With only one node, retaining and then trying to delete another node doesn't affect the 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 Linked List problems involving Selective Deletion, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: We will traverse the linked list, retaining the first m
nodes and deleting the next n
nodes. We repeat this process until we reach the end of the list.
1) Initialize a pointer `current` to the head of the list.
2) While `current` is not None:
a) Retain the first `m` nodes by moving the `current` pointer `m-1` times.
b) If `current` becomes None, return the modified list.
c) Start deleting the next `n` nodes by advancing another pointer.
d) Link the `current` node to the node after the `n` deleted nodes.
e) Move `current` to the next node after the deletions.
3) Return the modified head of the list.
⚠️ Common Mistakes
m
or n
nodes.Implement the code to solve the algorithm.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
# Function to edit the DNA sequence
def edit_dna_sequence(dna_strand, m, n):
current = dna_strand
while current:
# Retain the first m nodes
for i in range(1, m):
if current is None:
return dna_strand
current = current.next
if current is None:
return dna_strand
# Now current is at the m-th node
# We will delete the next n nodes
temp = current.next
for j in range(n):
if temp is None:
break
temp = temp.next
# Connect the m-th node to the node after the n deleted nodes
current.next = temp
# Move current to the next retained node
current = temp
return dna_strand
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
dna_strand
linked list to verify that the function correctly edits the list according to the m
and n
values.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 pointers.