2. Add Two Numbers
MediumSolutions in Python, Java, C++, TypeScript
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
Method Explanation
The problem asks us to add two non-negative integers represented by linked lists, where digits are stored in reverse order. This setup is convenient because it allows us to process the numbers from the least significant digit to the most significant, just like manual addition.
Solution
Add Two Numbers 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]:
# Create a dummy head for the result list to simplify edge cases.
dummy_head = ListNode(0)
# 'current' will point to the last node in the result list.
current = dummy_head
carry = 0
# Loop through lists l1 and l2 until both are None.
while l1 or l2:
# Get the value of the current node of l1, or 0 if l1 is None.
val1 = l1.val if l1 else 0
# Get the value of the current node of l2, or 0 if l2 is None.
val2 = l2.val if l2 else 0
# Calculate the sum of digits and the carry from the previous step.
total_sum = val1 + val2 + carry
# The new carry is the quotient of the sum divided by 10.
carry = total_sum // 10
# The new digit is the remainder of the sum divided by 10.
new_digit = total_sum % 10
# Create a new node with the digit and append it to the result list.
current.next = ListNode(new_digit)
# Move the current pointer to the new node.
current = current.next
# Move to the next node in l1 if it exists.
if l1:
l1 = l1.next
# Move to the next node in l2 if it exists.
if l2:
l2 = l2.next
# If there is a carry left over after the loop, create a new node for it.
if carry > 0:
current.next = ListNode(carry)
# The result list starts from the node after the dummy head.
return dummy_head.next
Add Two Numbers 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; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// Create a dummy head for the result list to simplify edge cases.
ListNode dummyHead = new ListNode(0);
// 'current' will point to the last node in the result list.
ListNode current = dummyHead;
int carry = 0;
// Loop through lists l1 and l2 until both are null.
while (l1 != null || l2 != null) {
// Get the value of the current node of l1, or 0 if l1 is null.
int val1 = (l1 != null) ? l1.val : 0;
// Get the value of the current node of l2, or 0 if l2 is null.
int val2 = (l2 != null) ? l2.val : 0;
// Calculate the sum of digits and the carry from the previous step.
int sum = val1 + val2 + carry;
// The new carry is the quotient of the sum divided by 10.
carry = sum / 10;
// The new digit is the remainder of the sum divided by 10.
int newDigit = sum % 10;
// Create a new node with the digit and append it to the result list.
current.next = new ListNode(newDigit);
// Move the current pointer to the new node.
current = current.next;
// Move to the next node in l1 if it exists.
if (l1 != null) {
l1 = l1.next;
}
// Move to the next node in l2 if it exists.
if (l2 != null) {
l2 = l2.next;
}
}
// If there is a carry left over after the loop, create a new node for it.
if (carry > 0) {
current.next = new ListNode(carry);
}
// The result list starts from the node after the dummy head.
return dummyHead.next;
}
}
Add Two Numbers 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) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
// Create a dummy head for the result list to simplify edge cases (like an empty result list).
ListNode* dummyHead = new ListNode(0);
// 'current' will point to the last node in the result list.
ListNode* current = dummyHead;
int carry = 0;
// Loop through lists l1 and l2 until both are null.
while (l1 != nullptr || l2 != nullptr) {
// Get the value of the current node of l1, or 0 if l1 is null.
int val1 = (l1 != nullptr) ? l1->val : 0;
// Get the value of the current node of l2, or 0 if l2 is null.
int val2 = (l2 != nullptr) ? l2->val : 0;
// Calculate the sum of digits and the carry from the previous step.
int sum = val1 + val2 + carry;
// The new carry is the quotient of the sum divided by 10.
carry = sum / 10;
// The new digit is the remainder of the sum divided by 10.
int new_digit = sum % 10;
// Create a new node with the digit and append it to the result list.
current->next = new ListNode(new_digit);
// Move the current pointer to the new node.
current = current->next;
// Move to the next node in l1 if it exists.
if (l1 != nullptr) {
l1 = l1->next;
}
// Move to the next node in l2 if it exists.
if (l2 != nullptr) {
l2 = l2->next;
}
}
// If there is a carry left over after the loop, create a new node for it.
if (carry > 0) {
current->next = new ListNode(carry);
}
// The result list starts from the node after the dummy head.
ListNode* result = dummyHead->next;
// Free the memory allocated for the dummy head.
delete dummyHead;
return result;
}
};
Add Two Numbers 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 {
// Create a dummy head for the result list to simplify edge cases.
let dummyHead = new ListNode(0);
// 'current' will point to the last node in the result list.
let current = dummyHead;
let carry = 0;
// Use p1 and p2 to iterate through the lists without modifying the original arguments.
let p1 = l1;
let p2 = l2;
// Loop until both lists are fully traversed.
while (p1 !== null || p2 !== null) {
// Get the value of the current node, or 0 if the list is exhausted.
const val1 = p1 !== null ? p1.val : 0;
const val2 = p2 !== null ? p2.val : 0;
// Calculate the sum of digits and the carry.
const sum = val1 + val2 + carry;
// The new carry is the integer part of the sum divided by 10.
carry = Math.floor(sum / 10);
// The new digit is the remainder.
const newDigit = sum % 10;
// Create a new node with the digit and append it to the result list.
current.next = new ListNode(newDigit);
// Move the current pointer forward.
current = current.next;
// Advance to the next nodes if they exist.
if (p1 !== null) p1 = p1.next;
if (p2 !== null) p2 = p2.next;
}
// If a carry remains after the loop, create a final node for it.
if (carry > 0) {
current.next = new ListNode(carry);
}
// The result list is the next node of the dummy head.
return dummyHead.next;
};
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.