Plus One: the idea to remember.
Increment a nonnegative integer represented as a most significant first digit array.
The core insight
Walk backward: increment the first digit below nine, otherwise set nines to zero and continue carrying.
Why it works
A carry affects only trailing nines; the first smaller digit absorbs it and leaves earlier digits unchanged.
The mistake to avoid
An all nine input needs a longer array beginning with one.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
// Java reference adapted from neetcode-gh/leetcode (MIT).
// Walk backward: increment the first digit below nine, otherwise set nines to zero and continue carrying.
public int[] plusOne(int[] digits) {
final int len = digits.length;
int[] newDigits = new int[len + 1];
int carry = 1;
int currSum = 0;
for (int i = len - 1; i >= 0; i--) {
currSum = digits[i] + carry;
if (currSum > 9) {
digits[i] = currSum % 10;
newDigits[i + 1] = digits[i];
carry = 1;
} else {
digits[i] = currSum;
newDigits[i + 1] = digits[i];
carry = 0;
break;
}
}
if (carry == 1) {
newDigits[0] = 1;
return newDigits;
}
return digits;
}Java reference adapted from neetcode-gh/leetcode · MIT license
Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.