Add Two Numbers II

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each node holds a single digit. Add the two numbers and return the sum as a linked list in the same most-significant-first order. Neither number has leading zeros except the number 0 itself.

30:00

Add Two Numbers II
medium
Free written solution
Topics
Companies

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each node holds a single digit. Add the two numbers and return the sum as a linked list in the same most-significant-first order. Neither number has leading zeros except the number 0 itself.

Example 1:
Input: {"l1":[7,2,4,3],"l2":[5,6,4]}
Output: [7,8,0,7]
Constraints:
  • The number of nodes in each list is in the range [1,100][1, 100].

  • 0≤Node.val≤90 \leq \text{Node.val} \leq 9

  • The input lists have no leading zeros, except the number 00 itself.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"l1":[7,2,4,3],"l2":[5,6,4]}

Walk l1: push digit 7 onto s1. The most significant digit goes to the bottom.

input lists (most significant digit first)

l1

7
→
2
→
4
→
3

l2

5
→
6
→
4

stacks (ones digit on top)

s1 (1)

7top

s2 (0)

(empty)

column sum

-

digit -

carry 0

answer, built by prepending (0 nodes)

head

→ null

Variables
VariableValue
s1[7]
DepthFunction Call
Stack empty
0/16