EasyNo. 0066

Plus One — LeetCode 66 Python Solution

Topics
Array, Math
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

PythonSolution
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

Time
O(n)where n is the length of the array
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0048Rotate ImageMedium
0189Rotate ArrayMedium
0204Count PrimesMedium
0335Self CrossingHard
0384Shuffle an ArrayMedium
0453Minimum Moves to Equal Array ElementsMedium

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.

Free to download. Check it runs on your machine, then pick a plan.