LeetCode 445: Add Two Numbers II Solution
Master LeetCode problem 445 (Add Two Numbers II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
445. Add Two Numbers II
Problem Explanation
Explanation
To solve this problem without reversing the input lists, we can use a stack to store the values of the nodes in each linked list. By doing this, we can add the numbers starting from the least significant digit. We iterate through the lists while pushing their values onto the stacks. Then, we pop the values from the stacks and add them while keeping track of the carry. We create a new linked list to store the sum in reverse order. At the end, we reverse the result linked list to get the final sum in the correct order.
Algorithm:
- Push the values of nodes in both linked lists onto two separate stacks.
- Pop the values from the stacks while adding them and keeping track of the carry.
- Create a new linked list to store the sum in reverse order.
- Reverse the result linked list to obtain the final sum.
Time Complexity: O(max(m, n)) where m and n are the lengths of the two input linked lists.
Space Complexity: O(m + n) to store the values in the stacks and the result linked list.
Solution Code
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
while (l1 != null) {
stack1.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
stack2.push(l2.val);
l2 = l2.next;
}
ListNode dummy = new ListNode(0);
int carry = 0;
while (!stack1.isEmpty() || !stack2.isEmpty() || carry != 0) {
int sum = carry;
if (!stack1.isEmpty()) sum += stack1.pop();
if (!stack2.isEmpty()) sum += stack2.pop();
carry = sum / 10;
sum %= 10;
ListNode newNode = new ListNode(sum);
newNode.next = dummy.next;
dummy.next = newNode;
}
return dummy.next;
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 445 (Add Two Numbers II)?
This page provides optimized solutions for LeetCode problem 445 (Add Two Numbers II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 445 (Add Two Numbers II)?
The time complexity for LeetCode 445 (Add Two Numbers II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 445 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 445 in Java, C++, or Python.