Plus One – Solution & Complexity
1. Add from the Least Significant Digit
- The last array element is the ones place, so addition starts there.
- If a digit is less than
9, adding one does not create a carry. - In that case, update the digit and return immediately.
2. Propagate Carry Through Nines
- A digit equal to
9becomes0after adding one and carries to the next digit on the left. - Continue scanning left while digits are
9. - This mirrors elementary addition.
3. Handle All-Nines Input
- If every digit was
9, the loop turns them all into0. - The result needs a new leading
1. - For example,
[9, 9]becomes[1, 0, 0].
4. Final Complete Solution
- The algorithm mutates the input list in place when possible and only allocates a new leading digit for all-nines cases.
- It scans from right to left once.
- Time complexity is O(n), and extra space complexity is O(1) besides the returned list.