Add Two Numbers
MediumNeetCode 150Top Interview 150 Linked ListBloombergMicrosoftAmazonGoogleMetaEarnInProblem
Two non-negative whole numbers are stored as linked lists, one digit per node, with the
ones digit first. So 342 is stored as 2 → 4 → 3.
Add the two numbers and return the sum as a list in the same format. Neither number has leading zeros, except the number 0 itself.
Constraints
- 1 ≤ length of each list ≤ 100
- 0 ≤ Node.val ≤ 9
- No leading zeros, except for the number 0
Examples: pick one to animate
Solutions
Time: Each pass consumes one digit from each list that still has one. The extra carry adds at most one more pass.
Space: Only a few pointers and the carry are kept. The output list is the answer, not extra working space.
The ones digit comes first in both lists, which is exactly the order you add by hand. Walk both lists together, add the two digits and the carry, write total mod 10 as a new node, and carry total divided by 10. Keep going while either list or the carry is non-zero, so a final carry gets its own node.