Skills101
← All coding problems

Add Two Numbers

mediumLinked List+20 XPTime limit 3s

Two non-negative numbers are stored as linked lists of digits in reverse order (the head is the ones digit): 2 → 4 → 3 means 342. Add them and print the sum in the same reversed format.

List format. A linked list is given as two lines: its length n, then its n values from head to tail (the second line is empty when n = 0). When you print a list, print its values on one line separated by spaces, or the word empty if it has no nodes.

Input: two lists of digits.

Output: the digits of the sum, ones digit first.

Constraints: 1 ≤ n₁, n₂ ≤ 10⁵; each value is a digit 0–9; numbers have no leading zeros (except the number 0 itself).

Think about it: this is column addition from school — walk both lists together, add digit + digit + carry. The numbers are far too long for any built-in integer type, so don't convert.

Sample input 1

3
2 4 3
3
5 6 4

Sample output 1

7 0 8

Sample input 2

1
0
1
0

Sample output 2

0

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.