Unit 5 Session 2 (Click for link to problem statements)
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: tail = Node("Saharah", prev=Node("K.K. Slider", prev=Node("Isabelle")))
Output: "Saharah K.K. Slider Isabelle"
Explanation: The function prints the values of the linked list from the tail to the head.
EDGE CASE
Input: tail = None
Output: (No output)
Explanation: When the linked list is empty, the function does not print anything.
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 Doubly Linked List problems, we want to consider the following approaches:
prev
pointersPlan the solution with appropriate visualizations and pseudocode.
General Idea: Traverse the doubly linked list from the tail to the head and print each node's value.
1) Start at the tail of the doubly linked list.
2) While the current node is not `None`, do the following:
a) Print the value of the current node.
b) Move to the previous node using the `prev` pointer.
3) Ensure that the values are separated by a space.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
class Node:
def __init__(self, value, next=None, prev=None):
self.value = value
self.next = next
self.prev = prev
def print_reverse(tail):
current = tail
while current:
if current.prev:
print(current.value, end=" ")
else:
print(current.value)
current = current.prev
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Example:
isabelle = Node("Isabelle")
kk_slider = Node("K.K. Slider")
saharah = Node("Saharah")
isabelle.next = kk_slider
kk_slider.next = saharah
saharah.prev = kk_slider
kk_slider.prev = isabelle
# Linked List: Isabelle <-> K.K. Slider <-> Saharah
print_reverse(saharah)
# Expected Output: "Saharah K.K. Slider Isabelle"
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
- Time Complexity: O(N) because we need to traverse all nodes in the doubly linked list.
- Space Complexity: O(1) because we are only using a constant amount of extra space for traversal.