Taro Logo

Plus One

#116 Most AskedEasy
Topics:
Arrays

You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. 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.

Example 1:

Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].

Example 2:

Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].

Example 3:

Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].

Constraints:

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum size (length) of the input `digits` array, and could it exceed standard integer limits?
  2. Can the input array be empty or contain `null`/`None`, and how should we handle that case?
  3. Does the input array ever contain leading zeros for numbers greater than zero (e.g., `[0, 1]` instead of `[1]`)?
  4. Should we modify the input array in-place to optimize space complexity, or is it expected that we return a brand new array?
  5. When a carry propagates all the way to the most significant digit (e.g., `[9, 9]`), should the resulting array correctly expand in size to `[1, 0, 0]`?

Brute Force Solution

Approach

Imagine you have a long sequence of digits written on paper representing a giant number, and you want to increase its value by one. The brute force strategy involves translating the paper digits into a standard number, adding one to it using normal math, and then breaking that new total back down into individual digits.

Here's how the algorithm would work step-by-step:

  1. Read the sequence of digits from left to right to figure out the exact mathematical value of the whole number.
  2. Perform the addition operation in your head to increase that total value by exactly one.
  3. Look at the new total value and extract each individual digit from it, one by one.
  4. Write down these new digits in the exact same order they appeared in the total value.
  5. Hand back the newly created collection of digits as your final answer.

Code Implementation

def plus_one(digits_sequence):
    # Convert individual digits into a single large integer for standard arithmetic addition
    combined_number = 0

    for current_digit in digits_sequence:
        combined_number = combined_number * 10 + current_digit

    # Increment the numerical value by one to fulfill the core requirement of the problem
    incremented_total = combined_number + 1

    # Convert the incremented total back into a string representation to isolate each digit
    total_as_string = str(incremented_total)

    # Extract each character from the string and convert it back into an integer digit
    result_digits = []

    for character_digit in total_as_string:
        result_digits.append(int(character_digit))

    return result_digits

Big(O) Analysis

Time Complexity
O(n) – To figure out the mathematical value of the whole number, we iterate through all n digits from left to right. Then, we perform a standard addition and extract the new digits back into a collection, which also scales proportionally with the number of digits in the new total value. This gives us roughly 2n operations as n grows large. Dropping the constant multiplier, the overall time complexity simplifies to O(n).
Space Complexity
O(n) – The brute-force strategy described in the steps requires parsing the input digits into a standard numeric type and then breaking the new total back down to extract each individual digit into a new collection. This process involves creating a new list or array of digits whose length scales directly with the input size N. Specifically, if the addition operation results in a carry that creates an extra digit, the output collection will require up to N plus one elements of auxiliary storage. Therefore, the extra memory used by the algorithm scales linearly with the input size N, simplifying to Big O notation of O(n).

Optimal Solution

Approach

Imagine you are writing down a number digit by digit on paper and you want to add one to the entire number. The most efficient strategy is to start at the very last digit on the right, just like you learned in school.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the rightmost digit of the number.
  2. If that digit is anything less than nine, simply increase it by one and you are completely finished with the entire problem.
  3. If that digit happens to be a nine, change it to a zero because adding one makes it roll over, and then step over to the next digit to the left.
  4. Repeat this check for each digit moving from right to left, increasing the digit by one if it is less than nine, or turning it into a zero and moving left if it is a nine.
  5. If you successfully update a digit that is not a nine, stop immediately and return your final result because the addition is done.
  6. If you reach the very beginning of the number and every single digit was a nine, turn them all into zeros and add a brand new one digit to the far left of the entire sequence.

Code Implementation

class Solution:
    def plusOne(self, digits_array: list[int]) -> list[int]:
        digit_index = len(digits_array) - 1

        while digit_index >= 0:
            # Digits below nine can absorb the increment without triggering a carry operation.
            if digits_array[digit_index] < 9:
                digits_array[digit_index] += 1
                return digits_array

            # Nines roll over to zero, requiring the carry to propagate leftward.
            digits_array[digit_index] = 0
            digit_index -= 1

        # All nines require a leading one because the number length expands by one.
        return [1] + digits_array

Big(O) Analysis

Time Complexity
O(n) – The input size n represents the total number of digits in the integer array. In the worst-case scenario, such as when every digit is a nine, the algorithm iterates backwards from the rightmost digit all the way to the very first element on the left. This requires visiting each of the n digits exactly once to change them to zeros, plus one final allocation if a new leading one is needed. Across all digits, the maximum number of operations scales linearly relative to n. Simplifying this total operation count yields a final time complexity of O(n).
Space Complexity
O(1) – The algorithm only uses a few constant variables to iterate through the digits from right to left, requiring no additional data structures. However, if every single digit is a nine, step 6 requires allocating a brand new array of size N plus one to hold the result. Excluding this worst-case output array that is strictly required to return the answer, the auxiliary space complexity for the in-place modifications is constant.

Edge Cases

Single digit array representing zero
How to Handle:
The loop processes the single zero, changes it to one, and returns the array correctly.
Array with all nines such as 999
How to Handle:
Every digit becomes zero during the carry propagation, and a new array of size n plus one with a leading one is created and returned.
Array ending in a zero such as 120
How to Handle:
The loop encounters zero at the least significant position, increments it to one, and terminates early without triggering further carries.
Large scale inputs with thousands of digits
How to Handle:
The algorithm operates in O(n) time complexity and uses O(1) extra space in place, scaling efficiently for massive arrays.
Language-specific integer overflow on conversion
How to Handle:
By manipulating the array elements directly as digits instead of parsing the entire array into a primitive integer type, we completely avoid overflow issues.
0/245 completed