Skip to the solution
MediumDSA11 min read

How do you add two numbers stored as linked lists?

1.1k views

The problem

Question presented to candidate: "Two non-negative integers are stored as linked lists, one digit per node, ones digit first: 342 is 2 โ†’ 4 โ†’ 3. Return their sum as a linked list in the same format. Please write it in Python."

What a strong answer should cover:

  • Column addition: walk both lists together, total = carry + x + y, append total % 10, carry total // 10.
  • Loop while either list or the carry remains, treating a missing digit as 0; a dummy head avoids a special case for the first node.
  • O(max(m, n)) time, output of at most max(m, n) + 1 nodes.
  • The forward-order follow-up: stacks (or reversing) plus prepending.
  • Python specifics: divmod(total, 10); Python ints never overflow, so "convert, add, convert back" does work for moderate sizes, but int(str) refuses inputs over 4300 digits by default and the interviewer is testing list handling anyway.

Clarifying questions expected:

  • "Ones digit first? Can the lists have different lengths?"
  • "May I modify the inputs, and how long can the numbers be?"

Code / implementation expected: Yes โ€” add_two_numbers(l1, l2) in Python, building a new list.

  • linked-list
  • math

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read ยท 10 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonDigit-by-digit addition with a carry (ones digit first)
PythonForward-order digits with stacks, including 30-digit numbers

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 46 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How does Quickselect find the kth smallest/largest element?

Continue