TIP102 Unit 5 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.
- 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 with nodes "Carp" -> "Dace" -> "Cherry Salmon", new_fish = "Rainbow Trout"
Output: "Carp -> Dace -> Cherry Salmon -> Rainbow Trout"
Explanation: The new fish "Rainbow Trout" is added to the end of the list.
EDGE CASE
Input: An empty linked list, new_fish = "Rainbow Trout"
Output: "Rainbow Trout"
Explanation: The list is empty, so the new fish becomes the head of 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, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: We need to handle two cases: when the list is empty and when the list is not empty. If the list is empty, we create a new node and return it as the head. If the list is not empty, we traverse to the end of the list and add the new node there.
1) Create a new node with the fish name `new_fish`.
2) If the head is `None`, return the new node as the head.
3) Set the current node to the head of the list.
4) While the current node's next pointer is not `None`:
a) Move to the next node.
5) Set the next pointer of the current node to the new node.
6) Return the head of the modified list.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
class Node:
def __init__(self, fish_name, next=None):
self.fish_name = fish_name
self.next = next
# For testing
def print_linked_list(head):
current = head
while current:
print(current.fish_name, end=" -> " if current.next else "\n")
current = current.next
def restock(head, new_fish):
new_node = Node(new_fish)
if head is None:
return new_node
current = head
while current.next:
current = current.next
current.next = new_node
return head
# Example Usage:
fish_list = Node("Carp", Node("Dace", Node("Cherry Salmon")))
print_linked_list(restock(fish_list, "Rainbow Trout")) # Output: "Carp -> Dace -> Cherry Salmon -> Rainbow Trout"
empty_list = None
print_linked_list(restock(empty_list, "Rainbow Trout")) # Output: "Rainbow Trout"
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
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.