Add Two Numbers Represented as Linked List in DSA Python - Time & Space Complexity
We want to understand how the time to add two numbers stored as linked lists grows as the numbers get longer.
How does the number of steps change when the linked lists have more digits?
Analyze the time complexity of the following code snippet.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def addTwoNumbers(l1, l2):
carry = 0
dummy = ListNode()
current = dummy
while l1 or l2 or carry:
val1 = l1.val if l1 else 0
val2 = l2.val if l2 else 0
total = val1 + val2 + carry
carry = total // 10
current.next = ListNode(total % 10)
current = current.next
if l1: l1 = l1.next
if l2: l2 = l2.next
return dummy.next
This code adds two numbers digit by digit, handling carry, and returns the sum as a linked list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that goes through each node of the linked lists.
- How many times: It runs once for each digit in the longer linked list, plus one extra if there is a carry at the end.
As the number of digits (nodes) increases, the loop runs more times, roughly once per digit.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The number of steps grows directly with the number of digits.
Time Complexity: O(n)
This means the time to add the numbers grows linearly with the number of digits.
[X] Wrong: "The time depends on the value of the numbers, not their length."
[OK] Correct: The code processes each digit once, so the length of the list matters, not the number's size.
Understanding this helps you explain how linked list traversal affects performance, a key skill in many coding challenges.
"What if the numbers were stored in forward order instead of reverse? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem context
The problem involves two linked lists where each node contains a single digit of a number, stored in reverse order.Step 2: Identify the main operation
We need to add these two numbers digit by digit, handling carry, and return the sum as a linked list.Final Answer:
Adding two numbers where each digit is stored in a node of a linked list -> Option AQuick Check:
Adding digits node-wise = Adding numbers represented as linked lists [OK]
- Confusing addition with sorting
- Thinking the digits are stored in normal order
- Ignoring carry during addition
Solution
Step 1: Check correct attribute assignment
class Node: def __init__(self, val=0, next=None): self.val = val self.next = next correctly assigns the value and next pointer using self.val and self.next.Step 2: Verify default parameters and syntax
class Node: def __init__(self, val=0, next=None): self.val = val self.next = next uses default values and proper syntax for linked list node creation.Final Answer:
class Node: def __init__(self, val=0, next=None): self.val = val self.next = next -> Option AQuick Check:
Correct node class syntax = class Node: def __init__(self, val=0, next=None): self.val = val self.next = next [OK]
- Reversing assignment order (val = self.val)
- Forgetting to use self for attributes
- Incorrect default parameters
def addTwoNumbers(l1, l2):
carry = 0
dummy = Node(0)
current = dummy
while l1 or l2 or carry:
val1 = l1.val if l1 else 0
val2 = l2.val if l2 else 0
total = val1 + val2 + carry
carry = total // 10
current.next = Node(total % 10)
current = current.next
if l1: l1 = l1.next
if l2: l2 = l2.next
return dummy.nextSolution
Step 1: Add digits with carry
Adding 2+5=7 (carry 0), 4+6=10 (carry 1), 3+4+1=8 (carry 0).Step 2: Form the resulting linked list
Digits are 7 -> 0 -> 8 representing 807, which is 342+465.Final Answer:
7 -> 0 -> 8 -> null -> Option DQuick Check:
342 + 465 = 807 = 7->0->8 [OK]
- Not handling carry correctly
- Mixing digit order in output
- Adding digits without carry
def addTwoNumbers(l1, l2):
carry = 0
dummy = Node(0)
current = dummy
while l1 or l2:
val1 = l1.val if l1 else 0
val2 = l2.val if l2 else 0
total = val1 + val2 + carry
carry = total // 10
current.next = Node(total % 10)
current = current.next
if l1: l1 = l1.next
if l2: l2 = l2.next
return dummy.nextSolution
Step 1: Analyze loop condition
The loop runs only while l1 or l2 exist, but if carry remains after both end, it is ignored.Step 2: Identify missing carry handling
Carry should be checked in loop condition to add an extra node if needed.Final Answer:
The loop misses processing carry after both lists end -> Option BQuick Check:
Loop must include carry to avoid missing last digit [OK]
- Ignoring carry after lists end
- Wrong loop condition
- Not updating current pointer
Solution
Step 1: Understand digit order difference
Forward order means most significant digit is at head, so addition must start from tail.Step 2: Reverse lists to reuse existing logic
Reversing lists makes digits least significant first, allowing normal addition and then reversing result restores order.Final Answer:
Reverse both lists, add as usual, then reverse the result -> Option CQuick Check:
Reverse to handle forward order addition [OK]
- Adding digits from head without reversing
- Ignoring digit order difference
- Converting to int may cause overflow
Ready to prove it?
Pass the test and this pattern moves unknown
