Plus One

Easyarraymath
Category: Math & Geometry
Companies that ask this question:
GoogleAmazonFacebook

Approach

Plus One

Problem Statement

You are given a large integer represented as an array of digits, where each digits[i] is the i-th digit. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.

Increment the large integer by one and return the resulting array of digits.

Examples

Example 1:

Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: 123 + 1 = 124

Example 2:

Input: digits = [9,9,9]
Output: [1,0,0,0]
Explanation: 999 + 1 = 1000

Approach

Right-to-Left with Carry

Start from rightmost digit, add 1, handle carry.

Algorithm:

  1. Start from last digit
  2. Add 1 to current digit
  3. If result < 10, done
  4. If result == 10, set to 0 and carry
  5. If all digits were 9, prepend 1

Complexity

  • Time: O(n)
  • Space: O(1) or O(n) if all 9s

Solution

java
1class Solution {
2    public int[] plusOne(int[] digits) {
3        int n = digits.length;
4        
5        for (int i = n - 1; i >= 0; i--) {
6            if (digits[i] < 9) {
7                digits[i]++;
8                return digits;
9            }
10            digits[i] = 0;
11        }
12        
13        // All digits were 9
14        int[] result = new int[n + 1];
15        result[0] = 1;
16        return result;
17    }
18}
Loading visualizer...