AlgoInsight

DSA problem

Add Two Numbers II

MediumLinked ListPattern: Linked Listtop600AmazonMicrosoftBloombergFacebookApple

You are given two non-empty linked lists representing two non-negative integers. Here the most-significant digit comes first, and each node contains a single digit. Add the two numbers and return the sum as a linked list, again with the most-significant digit first.

This is the natural variant of the classic "Add Two Numbers" problem, but the forward digit order is awkward: addition must proceed from the least-significant digit, which now sits at the tail of each list. A singly linked list cannot be walked backward, so you need a strategy to access the digits in reverse.

A common follow-up restriction is to solve it without modifying the input lists (so reversing them in place is discouraged). The cleanest non-destructive technique is to push every digit of each list onto its own stack. Popping the stacks then yields the digits from least-significant to most-significant, exactly the order addition needs.

The optimal approach loads both lists into two stacks, then repeatedly pops a digit from each (using 0 when a stack is empty), adds them with a carry, and builds the result. Because the result must be most-significant first, prepend each new node to the front of the output list so the digits naturally end up in the correct order. This runs in O(m + n) time and O(m + n) space.

Examples

Example 1
Input: l1 = [7,2,4,3], l2 = [5,6,4]
Output: [7,8,0,7]
Explanation: The numbers are 7243 and 564. Their sum is 7807, returned most-significant digit first as [7,8,0,7].
Example 2
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [8,0,7]
Explanation: The numbers are 243 and 564, which sum to 807, returned as [8,0,7].
Example 3
Input: l1 = [0], l2 = [0]
Output: [0]
Explanation: Both numbers are 0, so the sum is the single-node list [0].

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

linked-listmathstack

Browse all DSA problems