Plus One — LeetCode 66 Python Solution

EasyArrayMath
Problem
#66
Reading time
2 min

The problem

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.

Example

Input
digits = [1,2,3]
Output
[1,2,4]
Explanation
The array represents the integer 123.

Python solution

Python
class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        n = len(digits)
        for i in range(n - 1, -1, -1):
            digits[i] += 1
            digits[i] %= 10
            if digits[i] != 0:
                return digits
        return [1] + digits

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 66. Plus One is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

On study lists

This problem is on NeetCode 150 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 66. Plus One?
LeetCode 66. Plus One is rated Easy on LeetCode.
What is the time complexity of LeetCode 66. Plus One?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 66. Plus One?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 66. Plus One cover?
LeetCode 66. Plus One is tagged Array and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview