oneby7

Linked Lists Reversing and rewiring

300. Add Two Numbers

Medium 147 DSA Sheet

You are given two singly linked lists, l1 and l2. Each list holds a non-negative integer, one decimal digit per node, with the digits in reverse order: the head holds the ones digit, the next node holds the tens digit, and so on. Return the sum of the two numbers as a list in the same form.

The examples write a list as its values from the head on, so l1 = [4,1,6] is the list 4 → 1 → 6. Because the head holds the ones digit, that list is the number 614. The output shows the list you return the same way.

Example 1

l1
7083
l2
594
output
2034

Input: l1 = [7, 0, 8, 3], l2 = [5, 9, 4]

Output: [2,0,3,4]

Explanation: The lists hold 3,807 and 495, and 3,807 + 495 = 4,302. Written ones digit first, 4,302 is [2,0,3,4]. The second list is one digit shorter, so the last column adds the carry to the 3 alone.

Example 2

49
l1
89
l2
291
output

Input: l1 = [4, 9], l2 = [8, 9]

Output: [2,9,1]

Explanation: 94 + 98 = 192. The answer has one more digit than either list.

Example 3

0
l1
0
l2
0
output

Input: l1 = [0], l2 = [0]

Output: [0]

Explanation: The number 0 is written as [0], the only list that may end in a 0. The sum is 0, which is [0] too.

Check your understanding

Work out the answer for this input before you write any code.

l1 = [9, 9, 9], l2 = [1]

Constraints

  • 1 ≤ number of nodes in each list ≤ 105
  • 0 ≤ Node.val ≤ 9
  • The numbers have no leading zeros: the last node of a list is not 0, unless the list is just [0].

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.