Skip to content
CodeKruPro

Add two numbers stored as linked lists

Coding problemMediumAsked in: Adobe, Amazon, Apple, Google, Meta, Microsoft

Two non-negative whole numbers are stored in linked lists, one digit per node, with the lowest digit first. For example, the list 2, 4, 3 stands for the number 342. Return their sum as a linked list in the same form.

Neither number has leading zeros, except the number 0 itself, which is a single node holding 0. The numbers can have up to 100,000 digits, far more than any built-in integer type holds.

Examples

Example 1
Input: first = [2,4,3], second = [5,6,4]
Output: [7,0,8]
342 + 465 = 807.
Example 2
Input: first = [0], second = [0]
Output: [0]
Example 3
Input: first = [9,9,9,9], second = [1]
Output: [0,0,0,0,1]
9999 + 1 = 10000.

Constraints

  • Each list has between 1 and 100,000 nodes
  • Each node holds a digit from 0 to 9
  • The last node is not 0 unless the list is the single node 0

Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.

Run your code to see the results here.

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in