Add Two Numbers
- 1 min read
- LC-Medium
- Linked List
Solution
- If I have to explain this then you're at a really bad place, Faaez
| Time | Space | Explanation |
|---|
O(n) | O(n) | If considering output as extra space, then yes, it's O(n) |
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
head = l3 = ListNode()
carry = 0
while l1 or l2 or carry:
sum_ = carry
if l1:
sum_ += l1.val
l1 = l1.next
if l2:
sum_ += l2.val
l2 = l2.next
carry = sum_ // 10
l3.next = ListNode(sum_ % 10)
l3 = l3.next
return head.next