Skip to the solution
EasyDSA10 min read

How do you add one to a number represented as a digit array?

787 views

The problem

Question presented to candidate: "A non-negative integer is stored as a Python list of its digits, most significant digit first, so [1, 2, 9] means 129. Write a function that returns the digits of the number plus one."

What a strong answer should cover:

  • Walk from the last digit: a digit below 9 is incremented and the function returns; a 9 becomes 0 and the carry moves left.
  • If every digit was 9, return [1] followed by the zeros (one digit longer).
  • O(n) worst case, and only one digit touched for most inputs (early exit); O(1) extra space except the all-9s case.
  • Python specifics: int("".join(map(str, digits))) + 1 works because Python integers have no fixed size, but it is O(n) both ways and Python 3 refuses to convert strings of more than 4300 digits by default; range(len(digits) - 1, -1, -1) walks backwards; [1] + digits builds a new list.

Clarifying questions expected:

  • "Most significant digit first, and no leading zeros?"
  • "May I modify the input list?"

Code / implementation expected: Yes โ€” a Python plus_one(digits) with a backwards loop and the all-9s case.

  • arrays
  • 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

10 min read ยท 11 sections

Python code

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

PythonPlus one on ordinary inputs, trailing 9s and all 9s
PythonHow many digits are touched, and numbers too big for 64-bit integers
PythonGeneralisation: add any integer k to a digit array

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 14 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 nextEasy

How do you find the middle of a linked list?

Continue