Plus One using Python

The Plus One problem is one of the popular coding interview questions. It is asked in the coding interviews by companies like FAANG many times. Here you need to increment the last digit of an array by one and return the resulting array. So, if you want to learn how to solve the Plus One problem, this article is for you. In this article, I will take you through how to solve the plus one problem using Python.

Plus One Problem

In the plus one problem, you will be given an array of digits, and you need to increment the value of the last integer of the array by one to solve this problem. For example, look at the input and output array mentioned below:

  1. Input Array: [1, 2, 3]
  2. Output Array: [1, 2, 4]

In the above example, you can see that only the value of the last digit is increased by one to solve this problem. But in some scenarios, you will get only one integer in the array. For example, look at the input and output of a single-digit array as mentioned below:

  1. Input: [8], Output: [9]
  2. Input: [9], Output: [1, 0]

As incrementing the value of 9 gives 10, the output in such scenarios should be [1, 0].

Solving Plus One using Python

I hope you have now understood what plus one problem means. Below is how you can solve this problem using the Python programming language:

def plusOne(digits):
    n = len(digits) - 1
    while digits[n] == 9:
        digits[n] = 0
        n = n - 1
    if n < 0:
        digits = [1] + digits
    else:
        digits[n] = digits[n] + 1
    return digits

digits = [1, 2, 5, 7]
print(plusOne(digits))
Output: [1, 2, 5, 8]

So this is how you can solve the plus one problem using Python. You can find many more practice questions to improve your problem-solving skills using Python here.

Summary

In the plus one problem, you will be given an array of digits, and you need to increment the value of the last integer of the array by one to solve this problem. I hope you liked this article on how to solve the plus one problem using Python. Feel free to ask valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1538

Leave a Reply