{"id":2276,"date":"2024-03-09T06:54:55","date_gmt":"2024-03-09T06:54:55","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=2276"},"modified":"2025-04-08T12:57:17","modified_gmt":"2025-04-08T12:57:17","slug":"add-two-numbers","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/add-two-numbers\/","title":{"rendered":"Add Two Numbers Represented by Linked Lists (C++, Java)"},"content":{"rendered":"\n<p>Adding two numbers gives us the nostalgia for being in primary school. From counting the numbers on our fingers to counting the nodes of a <a href=\"https:\/\/favtutor.com\/blog-details\/linked-list-data-structure\">linked list<\/a>, we have all grown in different ways. To take one step further in the world of linked lists, we will be looking at a frequently asked problem: <a href=\"https:\/\/leetcode.com\/problems\/add-two-numbers\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">Add two numbers represented by linked lists<\/a>. This article will discuss the various approaches, ranging from brute force to the most optimized ones, along with their complexities and codes.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#8220;Add Two Numbers&#8221; Problem Statement<\/strong><\/h2>\n\n\n\n<p>In this problem, we are given two non-empty linked lists. <strong>Each linked list represents a number with its digits stored in reverse order, such that each node contains one digit. We need to add these numbers and then return the sum in the form of a new linked list.\u00a0<\/strong><\/p>\n\n\n\n<p><strong>Note:<\/strong> The numbers do not contain any leading zeroes, For eg. 000089.<\/p>\n\n\n\n<p>Let\u2019s understand this with an example.<\/p>\n\n\n\n<p><strong>Input:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-1ce0de7a44fdd05dc46afd561e862464\" style=\"background-color:#fedcba\"><code><strong>list1<\/strong> = &#91; 3, 4, 5 ]\n<strong>list2<\/strong> = &#91; 1, 8, 2 ]<\/code><\/pre>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-2756eb5a6810ff1e6b04771480366db2\" style=\"background-color:#fedcba\"><code><strong>sum<\/strong> = &#91; 4, 2, 8 ]<\/code><\/pre>\n\n\n\n<p><strong>Explanation:<\/strong><\/p>\n\n\n\n<p>List1 represents the number 543, as it is stored in reverse order, and list2 represents the number 281, so the sum of both numbers is 543 + 281, i.e. 824. So the output is [ 4, 2, 8 ] in reverse order in the form of a linked list.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/xfA9MqjVkKDo-3OLw_flm1YMpDNUFouqB2IVYD5JnOMTBdJoPT6KQr4eVTI-AxTeZ-6PJTxap7m-eRFDI3jD4PUXg2FLnH3dyPAhnggwAQJQeDeBc4xdlVRTJd5llBrdkzJAUmcsZDAUQn3VdhhievA\" alt=\"Example\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Brute Force Approach<\/strong><\/h2>\n\n\n\n<p>The easiest way to solve this problem is by traversing both lists and obtaining the number out of the lists. We can then add the number to get the sum and form the resultant linked list. Seems easy? Let\u2019s see the steps on how we can do it:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Initialize two integers num1 and num2 with 0.<\/li>\n\n\n\n<li>Traverse both linked lists one by one and apply simple mathematics, i.e, add the value of the node to the number and multiply the number by 10.<\/li>\n\n\n\n<li>Add both numbers to get their sum.<\/li>\n\n\n\n<li>Initialize a new node as head and take one temp node to create each digit and push it to the linked list.<\/li>\n\n\n\n<li>Now create the resultant linked list by using simple calculations, i.e., ( sum%10 ) to get the digit and ( sum\/10 ) to get the remaining digits.<\/li>\n\n\n\n<li>Repeat the above step until the sum >0.\u00a0<\/li>\n<\/ul>\n\n\n\n<p>The time complexity for this solution will be O(m+n), where m and n are the lengths of the respective linked lists. As we are traversing each of the linked lists to obtain the desired numbers.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Optimal Approach<\/strong><\/h2>\n\n\n\n<p>The naive approach requires us to traverse each linked list one by one and then add them to obtain the result. But we can reduce this complexity of two loops by traversing both lists at once and simultaneously adding the digits to obtain the sum. Thus, we can create the resultant linked list on the fly.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Algorithm<\/strong><\/h3>\n\n\n\n<p>We can follow these simple steps to solve it using the optimal approach:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Initialize two integers, <strong>digit and carry.<\/strong> The digit will hold the least significant digit of the sum and carry holds the digit that overflows.<\/li>\n\n\n\n<li>Create a dummy node,<strong> head. <\/strong>It represents the head of the new linked list and we will use it to print the linked list.<\/li>\n\n\n\n<li>Now, we need to traverse both lists at once, So we initialize temp1 and temp2 pointers to head1 and head2 of the lists.<\/li>\n\n\n\n<li>We will loop through the lists and perform the following operations:\n<ul class=\"wp-block-list\">\n<li>Calculate the<strong> Sum = temp1-&gt;val + temp2-&gt;val + carry.<\/strong><\/li>\n\n\n\n<li>To find the least significant digit and carry,<strong> digit = sum%10<\/strong> and <strong>carry = sum\/10.<\/strong><\/li>\n\n\n\n<li>Create a new node and set its value as the digit.<\/li>\n\n\n\n<li>Set this node as the next of the temp pointer, to assign it to the tail of the linked list.<\/li>\n\n\n\n<li>Increment all three-pointers, temp, temp1, and temp2.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Handle the case when the length of one list is greater than the other by looping through the larger list and assigning each digit to the sum.<\/li>\n\n\n\n<li><\/li>\n<\/ol>\n\n\n\n<p>Let\u2019s perform the above steps in this example:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/get9ZxtYNr9bIxZ2QRRfo82FeKzL0_QuVWbS4bPUquun-1P6pQWL68BkLcT2og6HV5n9Ym7UZO9GFaLKmOKWUNnmGDN1pJjSazifcyp-qU3N9HLlGcbjyzK-YoJaitruT0NhlSH8bkCN4wErjsKjN4E\" alt=\"Example\"\/><\/figure>\n\n\n\n<p><strong>Iteration 1: <\/strong>temp1 \u2192 val = 3, temp2 \u2192 val = 1, Carry = 0<\/p>\n\n\n\n<p>First add these to get the <strong>Sum<\/strong>, i.e. <strong>3 + 1 + Carry ( 0 ) = 4<\/strong><\/p>\n\n\n\n<p>Now, Digit = 4 and Carry = 0.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/RIut9xYOSvX0pRbsAuoMOicS8XL_dE7zsorsCGYR64-4bpnjxlXLrcj_KUY4xOOjmBOG-fStrvx_0_DpRn1yVzH8YlCx9RGFnZy4__-cclXplPMFCQTrFqKkByUQ1GwRMehtkpSczqv2367Txa23QVE\" alt=\"Iteration 1\"\/><\/figure>\n\n\n\n<p><strong>Iteration 2: <\/strong>temp1 \u2192 val = 4, temp2 \u2192 val = 8, Carry = 0<\/p>\n\n\n\n<p>First add these to get the <strong>Sum<\/strong>, i.e. <strong>4 + 8 + Carry ( 0 ) = 12<\/strong><\/p>\n\n\n\n<p>Now, Digit = 2 and Carry = 1.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/OlE-OwAnybz6EDBuTvpr7O8Goq6B7SIS6-t-NKJ9j-qDa2CTstj8Mt-t6ytak_ZKqjy7Jhl_EiaoSpIeiZNy4RW0xIUT-JG9Nzft7SNAwRAvCt2Xz9SojfD_v6Pr7kcege4mPX-Fg9lo6SyY9vXfOPw\" alt=\"Iteration 2\"\/><\/figure>\n\n\n\n<p><strong>Iteration 3: <\/strong>temp1 \u2192 val = 5, temp2 \u2192 val = 2, Carry = 1<\/p>\n\n\n\n<p>First add these to get the <strong>Sum<\/strong>, i.e. <strong>5 + 2 + Carry ( 1 ) = 8<\/strong><\/p>\n\n\n\n<p>Now, Digit = 8 and Carry = 0.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/ImYq8EhKc2X9QF6ZLHf6HAssS5pSgi--bMfEtlMcYUN5NkQnZZ5LErfAOeSrPAw7mfno8skhtNaYdHE8nHn0aH3JA7GkAEw2BaDrWrdaQ610uHgedv9LcyMuEwNtxojAY9-PnQLiLjPt9EZ5euszFY0\" alt=\"Iteration 3\"\/><\/figure>\n\n\n\n<p>Since both the lists are traversed, this is our resultant linked list.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>C++ Code<\/strong><\/h3>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-c++src&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;C++&quot;,&quot;modeName&quot;:&quot;cpp&quot;}\">#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\n\nclass ListNode{\n    public:\n    int val;\n    ListNode* next;\n   \n    ListNode(int val){\n        this-&gt;val = val;\n        this-&gt;next = NULL;\n    }\n};\n\nListNode* addTwoList(ListNode* temp1, ListNode* temp2){\n    int sum = 0, carry = 0, digit = 0;\n        ListNode* head = new ListNode(0);\n        ListNode* temp = head;\n       \n        while(temp1 and temp2){\n            sum = temp1-&gt;val + temp2-&gt;val + carry;\n            carry = sum\/10;\n            digit = sum%10;\n           \n            temp-&gt;next = new ListNode(digit);\n            temp1 = temp1-&gt;next;\n            temp2 = temp2-&gt;next;\n            temp = temp-&gt;next;\n        }\n       \n        while(temp1){\n            sum = temp1-&gt;val + carry;\n            carry = sum\/10;\n            digit = sum%10;\n           \n            temp-&gt;next = new ListNode(digit);\n            temp1 = temp1-&gt;next;\n            temp = temp-&gt;next;\n        }\n       \n        while(temp2){\n            sum = temp2-&gt;val + carry;\n            carry = sum\/10;\n            digit = sum%10;\n           \n            temp-&gt;next = new ListNode(digit);\n            temp2 = temp2-&gt;next;\n            temp = temp-&gt;next;\n        }\n       \n        if(carry){\n            temp-&gt;next = new ListNode(carry);\n        }\n       \n        return head-&gt;next;\n}\n\nvoid print(ListNode *head){\n    ListNode* temp = head;\n    while(temp){\n        cout&lt;&lt;temp-&gt;val&lt;&lt;&quot; &quot;;\n        temp = temp-&gt;next;\n    }\n    cout&lt;&lt;endl;\n}\n\nint main() {\n    ListNode* head1 = new ListNode(3);\n    head1-&gt;next = new ListNode(4);\n    head1-&gt;next-&gt;next = new ListNode(5);\n   \n    cout&lt;&lt;&quot;List1: &quot;;\n    print(head1);\n   \n    ListNode* head2 = new ListNode(1);\n    head2-&gt;next = new ListNode(8);\n    head2-&gt;next-&gt;next = new ListNode(2);\n   \n    cout&lt;&lt;&quot;List2: &quot; ;\n    print(head2);\n   \n    ListNode* newhead = addTwoList(head1, head2);\n    cout&lt;&lt;&quot;Resultant List: &quot;;\n    print(newhead);\n   \n    return 0;\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Java Code<\/strong><\/h3>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Java&quot;,&quot;modeName&quot;:&quot;java&quot;}\">class ListNode {\n    public int val;\n    public ListNode next;\n\n    public ListNode(int val) {\n        this.val = val;\n        this.next = null;\n    }\n}\n\npublic class Main {\n    public static ListNode addTwoLists(ListNode temp1, ListNode temp2) {\n        int sum = 0, carry = 0, digit = 0;\n        ListNode head = new ListNode(0);\n        ListNode temp = head;\n\n        while (temp1 != null &amp;&amp; temp2 != null) {\n            sum = temp1.val + temp2.val + carry;\n            carry = sum \/ 10;\n            digit = sum % 10;\n\n            temp.next = new ListNode(digit);\n            temp1 = temp1.next;\n            temp2 = temp2.next;\n            temp = temp.next;\n        }\n\n        while (temp1 != null) {\n            sum = temp1.val + carry;\n            carry = sum \/ 10;\n            digit = sum % 10;\n\n            temp.next = new ListNode(digit);\n            temp1 = temp1.next;\n            temp = temp.next;\n        }\n\n        while (temp2 != null) {\n            sum = temp2.val + carry;\n            carry = sum \/ 10;\n            digit = sum % 10;\n\n            temp.next = new ListNode(digit);\n            temp2 = temp2.next;\n            temp = temp.next;\n        }\n\n        if (carry != 0) {\n            temp.next = new ListNode(carry);\n        }\n\n        return head.next;\n    }\n\n    public static void print(ListNode head) {\n        ListNode temp = head;\n        while (temp != null) {\n            System.out.print(temp.val + &quot; &quot;);\n            temp = temp.next;\n        }\n        System.out.println();\n    }\n\n    public static void main(String[] args) {\n        ListNode head1 = new ListNode(3);\n        head1.next = new ListNode(4);\n        head1.next.next = new ListNode(5);\n\n        System.out.print(&quot;List1: &quot;);\n        print(head1);\n\n        ListNode head2 = new ListNode(1);\n        head2.next = new ListNode(8);\n        head2.next.next = new ListNode(2);\n\n        System.out.print(&quot;List2: &quot;);\n        print(head2);\n\n        ListNode newhead = addTwoLists(head1, head2);\n        System.out.print(&quot;Resultant List: &quot;);\n        print(newhead);\n    }\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Python Code<\/strong><\/h3>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">class ListNode:\n    def __init__(self, val):\n        self.val = val\n        self.next = None\n\ndef add_two_lists(temp1, temp2):\n    sum_val, carry, digit = 0, 0, 0\n    head = ListNode(0)\n    temp = head\n\n    while temp1 and temp2:\n        sum_val = temp1.val + temp2.val + carry\n        carry = sum_val \/\/ 10\n        digit = sum_val % 10\n\n        temp.next = ListNode(digit)\n        temp1 = temp1.next\n        temp2 = temp2.next\n        temp = temp.next\n\n    while temp1:\n        sum_val = temp1.val + carry\n        carry = sum_val \/\/ 10\n        digit = sum_val % 10\n\n        temp.next = ListNode(digit)\n        temp1 = temp1.next\n        temp = temp.next\n\n    while temp2:\n        sum_val = temp2.val + carry\n        carry = sum_val \/\/ 10\n        digit = sum_val % 10\n\n        temp.next = ListNode(digit)\n        temp2 = temp2.next\n        temp = temp.next\n\n    if carry:\n        temp.next = ListNode(carry)\n\n    return head.next\n\ndef print_list(head):\n    temp = head\n    while temp:\n        print(temp.val, end=&quot; &quot;)\n        temp = temp.next\n    print()\n\nif __name__ == &quot;__main__&quot;:\n    head1 = ListNode(3)\n    head1.next = ListNode(4)\n    head1.next.next = ListNode(5)\n\n    print(&quot;List1: &quot;, end=&quot;&quot;)\n    print_list(head1)\n\n    head2 = ListNode(1)\n    head2.next = ListNode(8)\n    head2.next.next = ListNode(2)\n\n    print(&quot;List2: &quot;, end=&quot;&quot;)\n    print_list(head2)\n\n    new_head = add_two_lists(head1, head2)\n    print(&quot;Resultant List: &quot;, end=&quot;&quot;)\n    print_list(new_head)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-842caf1ecde83daded0318e9613b9b05\" style=\"background-color:#fedcba\"><code>List1: 3 4 5&nbsp;\nList2: 1 8 2\nResultant List: 4 2 8<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><\/h3>\n\n\n\n<p>The time complexity for this approach is O(max(m,n))), where m and n are the lengths of the respective linked lists. Since we are traversing both lists at once, the maximum time required will be the max of the lengths of both.<\/p>\n\n\n\n<p>The space complexity is O(max(m,n)), as the resultant linked list will be of the size of the number of digits in the sum, which is a maximum of m, n and a carry of 1.\u00a0<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>Adding two numbers represented by the linked lists is an interesting problem and is asked frequently in the interviews. We can solve it using 2 different approaches as discussed in this article.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Adding two numbers gives us the nostalgia for being in primary school. From counting the numbers on our fingers to counting the nodes of a linked list, we have all grown in different ways. To take one step further in the world of linked lists, we will be looking at a frequently asked problem: Add [&hellip;]<\/p>\n","protected":false},"author":4,"featured_media":2278,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[7],"tags":[14,15],"class_list":["post-2276","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures-algorithms","tag-dsa","tag-leetcode"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/2276","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=2276"}],"version-history":[{"count":4,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/2276\/revisions"}],"predecessor-version":[{"id":7402,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/2276\/revisions\/7402"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/2278"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=2276"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=2276"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=2276"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}