Plus One

An array of digits represents a non-negative integer, most significant digit first. Return the array after adding one to the number.

EasyOptionalIn-place Manipulation
Solve This Problem

Video Solution

Video coming soon

We're producing a video walkthrough — check back soon.

Problem Overview

An array of digits represents a non-negative integer, most significant digit first. Return the array after adding one to the number.

Why solve this?

The array here isn't a list of independent numbers — it's a single number spread across cells. Getting comfortable with that framing, plus carry propagation from the least significant digit, sets up every later in-place digit and array manipulation problem.

Pattern Recognition

Whenever a prompt describes an array as the digits of one number, expect a reverse (right-to-left) traversal that propagates a carry, not a normal left-to-right scan.

Prerequisites

  • Reverse an Array — the right-to-left traversal direction here is the same instinct.

Hints

  1. Start from the last digit, not the first.
  2. Adding one only ever affects digits while there's a carry to propagate — most of the time you're done after the first digit.
  3. Handle the edge case where every digit is 9 (e.g. [9,9,9] -> [1,0,0,0]) — the array can grow by one digit.

Approach

Walk the array from the last digit to the first. Add 1 to the current digit; if the result is less than 10, no carry is needed and you can stop immediately. If it rolls over to 10, set that digit to 0 and continue the carry into the next digit to the left. If the carry survives past the first digit (every digit was 9), prepend a new leading 1.

Code

Solution.java
class Solution {
    public int[] plusOne(int[] digits) {
        for (int i = digits.length - 1; i >= 0; i--) {
            if (digits[i] < 9) {
                digits[i]++;
                return digits;
            }
            digits[i] = 0;
        }
        int[] withCarry = new int[digits.length + 1];
        withCarry[0] = 1;
        return withCarry;
    }
}
Time: O(n)Space: O(1) extra — O(n) only in the rare case the result must grow by one digit

Related Problems

Back to Arrays