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))) + 1works 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] + digitsbuilds 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.