Walk both lists, add, propagate carry
Each node is one digit, least-significant first. Add the two digits plus carry, emit sum % 10, keep sum // 10 as the next carry.
The lists already store the number backwards, so you can add from the heads the way you add on paper from the right. A leftover carry becomes one extra node.
Algorithm
- Start at both heads with
carry = 0. - While either list or the carry remains: add digits + carry, append
sum % 10, setcarry = sum // 10. - Return the built list.
- Time
- O(max(n, m))
- Space
- O(max(n, m))
class Solution: def addTwoNumbers(self, l1: list[int], l2: list[int]) -> list[int]: out: list[int] = [] carry = 0 i = 0 while i < len(l1) or i < len(l2) or carry: a = l1[i] if i < len(l1) else 0 b = l2[i] if i < len(l2) else 0 total = a + b + carry out.append(total % 10) carry = total // 10 i += 1 return out