445. Add Two Numbers II
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem requires adding two non-negative integers represented by linked lists. The most significant digit appears at the head of the list. This is the reverse of the standard "Add Two Numbers" problem where the least significant digit is at the head. The main challenge is that arithmetic addition is performed from right to left (least significant to most significant digit), while linked lists are typically traversed from left to right (most significant to least significant).
Solution
Add Two Numbers II in Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
s1 = []
s2 = []
# Push digits of l1 onto stack s1
while l1:
s1.append(l1.val)
l1 = l1.next
# Push digits of l2 onto stack s2
while l2:
s2.append(l2.val)
l2 = l2.next
carry = 0
result_head = None
# Perform addition using digits from stacks
while s1 or s2 or carry:
# Pop from stack or use 0 if stack is empty
val1 = s1.pop() if s1 else 0
val2 = s2.pop() if s2 else 0
total_sum = val1 + val2 + carry
carry = total_sum // 10
digit = total_sum % 10
# Create a new node for the current digit
# and prepend it to the result list
new_node = ListNode(digit)
new_node.next = result_head
result_head = new_node
return result_head
Add Two Numbers II in Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
import java.util.ArrayDeque;
import java.util.Deque;
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// Use Deque as a stack for better performance than legacy Stack class
Deque<Integer> s1 = new ArrayDeque<>();
Deque<Integer> s2 = new ArrayDeque<>();
// Push digits of l1 onto stack s1
while (l1 != null) {
s1.push(l1.val);
l1 = l1.next;
}
// Push digits of l2 onto stack s2
while (l2 != null) {
s2.push(l2.val);
l2 = l2.next;
}
int carry = 0;
ListNode resultHead = null;
// Perform addition using digits from stacks
while (!s1.isEmpty() || !s2.isEmpty() || carry != 0) {
// Pop from stack or use 0 if stack is empty
int val1 = s1.isEmpty() ? 0 : s1.pop();
int val2 = s2.isEmpty() ? 0 : s2.pop();
int sum = val1 + val2 + carry;
carry = sum / 10;
int digit = sum % 10;
// Create a new node for the current digit
ListNode newNode = new ListNode(digit);
// Prepend the new node to the result list. This builds the list in reverse.
newNode.next = resultHead;
resultHead = newNode;
}
return resultHead;
}
}
Add Two Numbers II in C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
#include <stack>
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
std::stack<int> s1, s2;
// Push digits of l1 onto stack s1
while (l1 != nullptr) {
s1.push(l1->val);
l1 = l1->next;
}
// Push digits of l2 onto stack s2
while (l2 != nullptr) {
s2.push(l2->val);
l2 = l2->next;
}
int carry = 0;
ListNode* resultHead = nullptr;
// Perform addition using digits from stacks
while (!s1.empty() || !s2.empty() || carry != 0) {
int val1 = 0;
if (!s1.empty()) {
val1 = s1.top();
s1.pop();
}
int val2 = 0;
if (!s2.empty()) {
val2 = s2.top();
s2.pop();
}
int sum = val1 + val2 + carry;
carry = sum / 10;
int digit = sum % 10;
// Create a new node for the current digit
ListNode* newNode = new ListNode(digit);
// Prepend the new node to the result list
newNode->next = resultHead;
resultHead = newNode;
}
return resultHead;
}
};
Add Two Numbers II in TypeScript
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
const s1: number[] = [];
const s2: number[] = [];
// Push digits of l1 onto stack s1
let curr1 = l1;
while (curr1) {
s1.push(curr1.val);
curr1 = curr1.next;
}
// Push digits of l2 onto stack s2
let curr2 = l2;
while (curr2) {
s2.push(curr2.val);
curr2 = curr2.next;
}
let carry = 0;
let resultHead: ListNode | null = null;
// Perform addition using digits from stacks
while (s1.length > 0 || s2.length > 0 || carry !== 0) {
// Pop from stack or use 0 if stack is empty
const val1 = s1.pop() ?? 0;
const val2 = s2.pop() ?? 0;
const sum = val1 + val2 + carry;
carry = Math.floor(sum / 10);
const digit = sum % 10;
// Create a new node for the current digit
// and prepend it to the result list
const newNode = new ListNode(digit);
newNode.next = resultHead;
resultHead = newNode;
}
return resultHead;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.