
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
Editorial
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. | ||||
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