TIP102 Unit 5 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: head = Node("shake tree") -> Node("dig fossils") -> Node("catch bugs"), task = "check turnip prices"
Output: Node("check turnip prices") -> Node("shake tree") -> Node("dig fossils") -> Node("catch bugs")
Explanation: The new task is added to the front of the task list.
EDGE CASE
Input: head = None, task = "start new task"
Output: Node("start new task")
Explanation: When the initial task list is empty, the new task becomes the head.
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: Insert a new node at the beginning of the linked list and make it the new head.
1) Create a new node with the given task.
2) Set the new node's next to the current head.
3) Return the new node as the new head.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
# For testing
def print_linked_list(head):
current = head
while current:
print(current.value, end=" -> " if current.next else "\n")
current = current.next
def add_task(head, task):
new_node = Node(task)
new_node.next = head
return new_node
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Example:
task_1 = Node("shake tree")
task_2 = Node("dig fossils")
task_3 = Node("catch bugs")
task_1.next = task_2
task_2.next = task_3
# Linked List: shake tree -> dig fossils -> catch bugs
print_linked_list(add_task(task_1, "check turnip prices"))
Expected Output: check turnip prices -> shake tree -> dig fossils -> catch bugs
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.