2. Add Two Numbers
Asked at 33Bloomberg85Microsoft82Amazon80Google79Meta75Apple40EarnIn100Adobe91Wix87LTI81Jane Street68Airbnb66AQR Capital Management66Zoho65SAP62Arista Networks60ByteDance59Palo Alto Networks59Nvidia55Capgemini52Cisco51EPAM Systems51tcs50Infosys50Yandex49Media.net48Oracle45IBM44Capital One43Snowflake39Goldman Sachs36DoorDash29Uber22
Problem
Two non-empty linked lists hold non-negative integers with their digits in reverse order (ones digit first). Return their sum as a linked list in the same format.
Example: 2→4→3 + 5→6→4 → 7→0→8 (342 + 465 = 807)
Digits are stored least-significant first, so add node by node with a carry, like grade-school addition.
2 -> 4 -> 3 (342)
+ 5 -> 6 -> 4 (465)
= 7 -> 0 -> 8 (807) carry: 0, 1, 0
Complexity: O(max(m, n)).
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
dummy = tail = ListNode()
carry = 0
while l1 or l2 or carry:
s = carry + (l1.val if l1 else 0) + (l2.val if l2 else 0)
carry, d = divmod(s, 10)
tail.next = ListNode(d)
tail = tail.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return dummy.next
assert list_vals(Solution().addTwoNumbers(make_list([2, 4, 3]), make_list([5, 6, 4]))) == [7, 0, 8]
assert list_vals(Solution().addTwoNumbers(make_list([9, 9, 9]), make_list([1]))) == [0, 0, 0, 1]
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(), tail = dummy;
int carry = 0;
while (l1 != null || l2 != null || carry != 0) {
int s = carry;
if (l1 != null) { s += l1.val; l1 = l1.next; }
if (l2 != null) { s += l2.val; l2 = l2.next; }
carry = s / 10;
tail = tail.next = new ListNode(s % 10);
}
return dummy.next;
}
}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
dummy := &ListNode{}
tail, carry := dummy, 0
for l1 != nil || l2 != nil || carry > 0 {
s := carry
if l1 != nil {
s, l1 = s+l1.Val, l1.Next
}
if l2 != nil {
s, l2 = s+l2.Val, l2.Next
}
carry = s / 10
tail.Next = &ListNode{Val: s % 10}
tail = tail.Next
}
return dummy.Next
}