LL 15 - Add Two Numbers

Chetan DattaChetan Datta
2 min read

Problem

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example 1:

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

Example 2:

Input: l1 = [0], l2 = [0]
Output: [0]

Example 3:

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]

Constraints:

  • The number of nodes in each linked list is in the range [1, 100].

  • 0 <= Node.val <= 9

  • It is guaranteed that the list represents a number that does not have leading zeros.

Solution

We take corresponding nodes from the two lists, calculate the resultant sum, and place it in a new node, which is then added to the answer head linked list. If any carry is generated, we account for it in the next node addition. Initially, we use a dummy node for the answer linked list as the head to reduce condition checks and improve code readability.

Time - O(n)

Space - O(n)

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode temp1 = l1;
        ListNode temp2 = l2;

        int carry = 0;

        ListNode head = new ListNode(-1);
        ListNode curr = head;

        while(temp1!=null || temp2!=null){
            int sum = carry;

            if(temp1!=null) sum += temp1.val;
            if(temp2!=null) sum += temp2.val;

            carry = sum/10;

            ListNode newNode = new ListNode(sum%10);
            curr.next =newNode;
            curr = newNode;

            if(temp1!=null) temp1 = temp1.next;
            if(temp2!=null) temp2 = temp2.next;
        }

        if(carry==1){
            ListNode newNode = new ListNode(1);
            curr.next = newNode;
        }

        return head.next;
    }
}
0
Subscribe to my newsletter

Read articles from Chetan Datta directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Chetan Datta
Chetan Datta

I'm someone deeply engrossed in the world of software developement, and I find joy in sharing my thoughts and insights on various topics. You can explore my exclusive content here, where I meticulously document all things tech-related that spark my curiosity. Stay connected for my latest discoveries and observations.