150NeetCode 150

140.Plus One

EasyMath & Geometry ยท 5/8

Problem

A large non-negative integer is stored as an array digits, most significant digit first, with no leading zeros (except the number 0 itself). Add one to the integer and return the resulting array of digits.

Examples

Input:  digits = [1, 2, 3]
Output: [1, 2, 4]
Explanation: 123 + 1 = 124.
Input:  digits = [4, 3, 2, 9]
Output: [4, 3, 3, 0]
Explanation: 4329 + 1 = 4330 โ€” the 9 rolls over and carries.
Input:  digits = [9, 9, 9]
Output: [1, 0, 0, 0]
Explanation: 999 + 1 = 1000 โ€” the array grows by one digit.

Constraints

  • 1 <= digits.length <= 100
  • 0 <= digits[i] <= 9
  • digits does not contain any leading 0's.

๐Ÿ’ก Key Insight

Adding one only affects the trailing run of 9s: each 9 becomes 0 and passes a carry left, and the first non-9 digit just increments โ€” then you can stop immediately. Only when every digit is 9 does the array grow, and the answer is then always 1 followed by zeros.

Brute Force (Convert to a Number)

TimeO(n)SpaceO(n)

Intuition

Turn the array into a number, add one, and turn it back into digits. This is how you'd do it by hand, but up to 100 digits overflows long (max โ‰ˆ 9.2 ร— 10^18, 19 digits). It only works with BigInteger, which hides the real lesson and costs extra allocation.

Algorithm

  1. Build a BigInteger from the digits.
  2. Add BigInteger.ONE.
  3. Convert its decimal string back into an int[].

Visualization

[4,3,2,9] -> "4329" -> 4329 + 1 = 4330 -> "4330" -> [4,3,3,0]
with a long, 100 nines would overflow -> must use BigInteger

Code

java
import java.math.BigInteger;

class Solution {
    public int[] plusOne(int[] digits) {
        StringBuilder sb = new StringBuilder();
        for (int d : digits) sb.append(d);
        // long would overflow for more than 18 digits
        String sum = new BigInteger(sb.toString()).add(BigInteger.ONE).toString();
        int[] result = new int[sum.length()];
        for (int i = 0; i < sum.length(); i++) result[i] = sum.charAt(i) - '0';
        return result;
    }
}

Complexity

  • Time: O(n) โ€” building, adding and converting are linear in the number of digits.
  • Space: O(n) โ€” the string and big integer.

Complexity Comparison

Approach Time Space
BigInteger O(n) O(n)
Carry Simulation O(n) O(1) / O(n)
Early Exit O(n) worst, O(1) typical O(1) / O(n)

Common Pitfalls

  • Converting to int/long โ€” overflows for long inputs.
  • Forgetting the all-9s case, which needs one more digit.
  • Iterating left to right โ€” carries propagate from the least significant (rightmost) digit.
  • Copying the old digits into the grown array โ€” they are all 0 already, so only result[0] = 1 is needed.