DSA Tracker

Visualize

Add Two Numbers

Storing digits least-significant-first isn't an arbitrary quirk — it's exactly the direction elementary-school addition runs in, so the two lists can be walked together node-by-node with no need to reverse anything first. Each step adds the two current digits plus whatever carried over from the previous step, banking the ones digit into the result and carrying the tens digit forward, exactly like adding on paper right-to-left. A dummy head simplifies building the result list, and the loop keeps going as long as either list still has digits or a carry remains.

Details

Animated on: Add two numbers as reversed-digit lists: list1=[2,4,3]→342, list2=[5,6,4]→465, sum=807→result=[7,0,8]

Problem:Add Two NumbersMedium

Linked List

step 1 / 6

2
[0]
4
[1]
3
[2]
5
[3]
6
[4]
4
[5]

Input: list1=[2,4,3] representing 342 (reversed), list2=[5,6,4] representing 465 (reversed). Combined array shows all digits. carry=0 initially. Pointer i=0 for list1 (val2), pointer j=0 for list2 (val5).

  • l1=0· arr[0] = 2
  • l2=3· arr[3] = 5
Pseudocode
1FUNCTION addTwoNumbers(l1, l2):
2 make a dummy start node; tail = dummy; carry = 0
3 WHILE l1 has nodes or l2 has nodes or carry is not 0:
4 sum = (l1's value, or 0 if none) + (l2's value, or 0 if none) + carry
5 carry = sum divided by 10, rounded down
6 attach a new node holding (sum mod 10) after tail
7 tail = the node after tail
8 if l1 has nodes, move l1 to the next node
9 if l2 has nodes, move l2 to the next node
10 END WHILE
11 RETURN the node after dummy
12END FUNCTION

← / → step · space play · Home restart

Every step in words

Show all 6 steps
  1. Input: list1=[2,4,3] representing 342 (reversed), list2=[5,6,4] representing 465 (reversed). Combined array shows all digits. carry=0 initially. Pointer i=0 for list1 (val2), pointer j=0 for list2 (val5).
  2. Step 1: sum = l1[idx0]=2 + l2[idx3]=5 + carry=0 = 7. carry = Math.floor(7/10) = 0. digit = 7%10 = 7. Create node 7. Result so far: [7]. l1 moves to idx1(val4), l2 moves to idx1(val6).
  3. Step 2: sum = l1[idx1]=4 + l2[idx4]=6 + carry=0 = 10. carry = Math.floor(10/10) = 1. digit = 10%10 = 0. Create node 0. Result so far: [7, 0]. l1 moves to idx2(val3), l2 moves to idx2(val4).
  4. Step 3: sum = l1[idx2]=3 + l2[idx5]=4 + carry=1 = 8. carry = Math.floor(8/10) = 0. digit = 8%10 = 8. Create node 8. Result so far: [7, 0, 8]. l1 and l2 both move past end (null). carry=0, loop condition l1||l2||carry is now false, so loop ends.
  5. Step 4: Loop condition checked: l1=null, l2=null, carry=0. All false, exit while loop. Final result [7,0,8] represents 807 (342+465=807).
  6. Return [7,0,8]: the sum list where idx0=7 (units), idx1=0 (tens), idx2=8 (hundreds). 342 + 465 = 807 verified. Each digit added with carry propagation from right to left.

Now solve it yourself

Watching is the first half. The second is writing it without the animation.