DSA AnimatorREVISION VIDEOS
← Back to problems
New

Add Two Numbers — LeetCode 2 video explanation

Two numbers are stored as linked lists, with digits in reverse order. Return their sum as a linked list in the same form.

Loading videos…

DSA Animator › DSA Revision › Linked List › Add Two Numbers

Key moments in the Add Two Numbers video

0:03Problem0:10Example0:20Brute force0:27Key idea0:39Dry run0:49Code1:03Takeaway

What you will learn

Remember: reversed digits mean you can add from the head. Don't forget a final carry node. The video solves Add Two Numbers (LeetCode 2, Medium) with the Linked List Arithmetic pattern from the Linked List topic, and you can replay every step in the interactive Add Two Numbers animation.

Add Two Numbers video transcript

Problem

Two numbers are stored as linked lists, with digits in reverse order. Return their sum as a linked list in the same form.

Example

2, 4, 3 is 342, and 5, 6, 4 is 465. The sum is 807, so the answer is 7, 0, 8.

Brute force

Converting the lists to integers can overflow for long lists. Instead, add digit by digit, like on paper.

Key idea

The lowest digit comes first, which is exactly where addition starts. Add the two digits plus the carry, write the sum mod 10, and carry the rest. Keep going while either list or the carry remains.

Dry run

2 plus 5 is 7, with no carry. 4 plus 6 is 10, so write 0 and carry 1. 3 plus 4 plus 1 is 8. The result is 7, 0, 8.

Code

In code, use a dummy head and a carry variable. Loop while either list or the carry is left, adding the available digits. Append sum mod 10, and set carry to sum divided by 10. It's O of max of m and n time.

Takeaway

Remember: reversed digits mean you can add from the head. Don't forget a final carry node.

More Linked List revision videos

← All 185 DSA revision videos