Tutorialspoint
Problem
Solution
Submissions

Add Two Numbers

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 8

Write a Java program to add two numbers represented by linked lists. You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each node 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:
    • The number represented by l1 is 342 (3 -> 4 -> 2 in reverse).
    • The number represented by l2 is 465 (4 -> 6 -> 5 in reverse).
    • 342 + 465 = 807.
    • The result in reverse order is 7 -> 0 -> 8.
Example 2
  • Input: l1 = [9,9,9,9], l2 = [9,9,9]
  • Output: [8,9,9,0,1]
  • Explanation:
    • The number represented by l1 is 9999 (in reverse).
    • The number represented by l2 is 999 (in reverse).
    • 9999 + 999 = 10998.
    • The result in reverse order is 8 -> 9 -> 9 -> 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
  • Time Complexity: O(max(n, m)) where n and m are the lengths of the two linked lists
  • Space Complexity: O(max(n, m)) for the result linked list
Linked ListNumberGoogleAmazonTutorialspoint
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Create a dummy head node to simplify the linked list creation
  • Traverse both lists simultaneously
  • Add the values of nodes from both lists along with any carry from previous addition
  • Create a new node with the sum modulo 10 and update the carry
  • Continue traversing until both lists are exhausted and carry is zero

Steps to solve by this approach:

 Step 1: Create a dummy head node to simplify the linked list creation process.
 Step 2: Initialize a variable 'carry' to 0 to handle any carry from digit addition.
 Step 3: Traverse both linked lists simultaneously while either list has nodes or there's a carry value.
 Step 4: For each position, get the values from both lists (or use 0 if a list has ended).
 Step 5: Add the values from both lists and the carry from the previous step.
 Step 6: Create a new node with the value (sum % 10) and update the carry to (sum / 10).
 Step 7: Move to the next nodes in both lists if available.
 Step 8: After the loop, if there's still a carry, add a new node with the carry value.
 Step 9: Return the next node of the dummy head, which is the head of the result linked list.

Submitted Code :