InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Linked List

Add Two Numbers

medium Original ↗ 00:00

Problem

Two non-negative integers are stored in two singly linked lists, one digit per node, with the least significant digit first. Add the two numbers and return the sum as a linked list in the same reversed-digit format.

Neither number has leading zeros, except the number 0 itself (a single 0 node).

Examples

  • Input: l1 = 2 -> 4 -> 3, l2 = 5 -> 6 -> 4 → Output: 7 -> 0 -> 8 The lists encode 342 and 465; 342 + 465 = 807, stored as 7,0,8.
  • Input: l1 = 0, l2 = 0 → Output: 0 0 + 0 = 0.
  • Input: l1 = 9 -> 9 -> 9, l2 = 1 → Output: 0 -> 0 -> 0 -> 1 999 + 1 = 1000; the final carry creates a new most-significant digit.

Constraints

  • Each list has [1, 100] nodes.
  • 0 <= Node.val <= 9
  • No leading zeros (other than the number 0).

Think about it first

Hint 1 Both lists store the least significant digit first, so they already start at the digit where column addition begins.
Hint 2 Walk both lists together. At each position the output digit is (d1 + d2 + carry) % 10 and the new carry is the integer quotient by 10. What happens when one list is shorter?
Hint 3 Loop while either list has nodes or the carry is nonzero, treating a missing node as digit 0. A dummy head keeps the list-building clean. One pass, no number conversion needed.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug