Plus One
Easy · rating 950 · arrays, math
Read a sequence of space-separated digits representing a non-negative integer (most significant digit first, no leading zeros unless the number is 0). Print the digits of that number plus one, with no leading zeros and no spaces.
Editorial
Plus One is a common array/math interview problem: given the digits of a number (most significant first), add one and return the resulting digits — handling the carry that can ripple through trailing 9s.
Approach
Walk from the least significant digit. If a digit is below 9, increment it and you're done. If it's 9, set it to 0 and carry left. If every digit was 9 (999 → 1000), prepend a leading 1.
for i in range(len(d)-1, -1, -1):
if d[i] < 9:
d[i] += 1
return d
d[i] = 0
return [1] + dComplexity
Time: O(n). Space: O(1) (O(n) only in the all-nines case).