Plus One — LeetCode 66 Python Solution
- Problem
- #66
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
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
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] + digitsComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array |
| Space | O(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.