Tutorialspoint
Problem
Solution
Submissions

Add Two Numbers in Linked Lists

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to add two non-negative integers represented by linked lists, where each node contains a single digit. The digits are stored in reverse order, and each of their nodes contains a single digit. Return the sum as a linked list.

Example 1
  • Input: l1 = [2,4,3], l2 = [5,6,4]
  • Output: [7,0,8]
  • Explanation:
    • 342 + 465 = 807
    • Step 1: Add the first nodes: 2 + 5 = 7, carry = 0
    • Step 2: Add the second nodes: 4 + 6 = 10, carry = 1, result node = 0
    • Step 3: Add the third nodes: 3 + 4 + 1(carry) = 8, carry = 0
    • Step 4: Final result is [7,0,8] which represents 807.
Example 2
  • Input: l1 = [0], l2 = [0]
  • Output: [0]
  • Explanation:
    • 0 + 0 = 0
    • Step 1: Add the only nodes: 0 + 0 = 0, carry = 0
    • Step 2: Final result is [0] which represents 0.
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 l1 and l2
  • Space Complexity: O(max(n, m))
Linked ListNumberHCL TechnologiesD. E. Shaw
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

  • Traverse both lists simultaneously
  • Keep track of the carry as you add digits
  • Create a new node for each sum digit
  • Remember to handle the case when one list is longer than the other
  • Don't forget to add an extra node if there's a final carry

Steps to solve by this approach:

 Step 1: Create a dummy head node to simplify the code.
 Step 2: Initialize variables to track current node and carry value.
 Step 3: Loop through both lists simultaneously until both lists are exhausted.
 Step 4: For each position, add the values from both lists and the carry.
 Step 5: Create a new node with the ones digit of the sum and update the carry.
 Step 6: After the main loop, check if there's a remaining carry to add a final node.
 Step 7: Return the linked list starting from the dummy head's next node.

Submitted Code :