Back to DSA

Add Two Numbers

medium
Acceptance: 45%
Linked List

Two non-empty linked lists represent two non-negative integers with their digits stored in reverse order (least significant digit first). Each node holds a single digit. Add the two numbers and return the result as a new linked list, also in reverse digit order.

Examples

Example 1:
Input:l1 = [3,5,2], l2 = [4,7,1]
Output:[7,2,4]
Example 2:
Input:l1 = [8,9], l2 = [5]
Output:[3,0,1]

Hints

00:00
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode curr = dummy;
        int carry = 0;
        while (l1 != null || l2 != null || carry != 0) {
            int sum = carry;
            if (l1 != null) { sum += l1.val; l1 = l1.next; }
            if (l2 != null) { sum += l2.val; l2 = l2.next; }
            carry = sum / 10;
            curr.next = new ListNode(sum % 10);
            curr = curr.next;
        }
        return dummy.next;
    }
}
Time complexityO(max(n, m))
Space complexityO(max(n, m))