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.
HAPPY CASE
Input: head_a = Node(2, Node(4, Node(3))) # 342
head_b = Node(5, Node(6, Node(4))) # 465
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807. The result is represented as 7 -> 0 -> 8.
EDGE CASE
Input: head_a = Node(9, Node(9, Node(9))) # 999
head_b = Node(1) # 1
Output: 0 -> 0 -> 0 -> 1
Explanation: 999 + 1 = 1000. The result is represented as 0 -> 0 -> 0 -> 1.
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 Addition and Carry Management, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: We will traverse both linked lists, adding the corresponding digits along with any carry-over from the previous step. The sum will be stored in a new linked list.
1) Initialize a temporary `head` node to simplify edge cases.
2) Initialize a variable `carry` to `0`.
3) Traverse both linked lists simultaneously:
a) Add the values of the current nodes and the `carry`.
b) Create a new `node` with the digit value of `sum % 10`.
c) Update the `carry` to `sum // 10`.
d) Move to the next nodes in both lists.
4) If any `carry` remains after traversal, add a new `node` with the `carry` value.
5) Return the next `node` of the temporary `head` (skipping the initial dummy node).
⚠️ Common Mistakes
Implement the code to solve the algorithm.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
# Function to add two numbers represented as linked lists
def add_two_numbers(prize_a, prize_b):
temp_head = Node(0) # Temporary head node to simplify edge cases
current = temp_head
carry = 0
while prize_a or prize_b or carry:
sum_value = carry
if prize_a:
sum_value += prize_a.value
prize_a = prize_a.next
if prize_b:
sum_value += prize_b.value
prize_b = prize_b.next
# Calculate new carry and the digit to store in the node
carry = sum_value // 10
new_node = Node(sum_value % 10)
current.next = new_node
current = current.next
return temp_head.next
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
head_a
and head_b
linked lists to verify that the function correctly adds the two numbers.Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume N
represents the number of nodes in the longer of the two linked lists.
O(N)
because each node is visited exactly once.O(N)
because a new linked list is created to store the result.