Skip to content

Plus One

Given a large integer represented as an array of digits, increment it by one.

You need to solve this problem efficiently.

InputOutputExplanation
Example 1Result 1Explanation for example 1
Example 2Result 2Explanation for example 2
  • Constraint 1 for Plus One
  • Constraint 2
  • Constraint 3
ApproachTimeSpaceBest When
IterateO(n)O(1)When applicable
RecursiveO(n)O(1)When applicable
MathO(n)O(1)When applicable
★ Recommended

This approach provides an efficient solution for plus one.

⏱ Time O(n) Single pass 💾 Space O(1) Minimal storage
plus_one_iterate.py
from typing import List
def plus_one_iterate(digits: List[int]) -> List[int]:
"""Increment number by one using iteration."""
carry = 1
for i in range(len(digits) - 1, -1, -1):
digits[i] += carry
if digits[i] < 10:
return digits
digits[i] = 0
return [1] + digits
# Test cases
print(plus_one_iterate([1, 2, 3])) # [1, 2, 4]
print(plus_one_iterate([9, 9, 9])) # [1, 0, 0, 0]
🎯 Interview Favourite

This approach provides an efficient solution for plus one.

⏱ Time O(n) Single pass 💾 Space O(1) Minimal storage
plus_one_recursive.py
# Python Solution
# Problem: plus-one
# Approach: recursive
# Implementation placeholder for plus_one_recursive
# This file is auto-generated and should contain the solution code.
def plus_one_recursive():
pass
if __name__ == "__main__":
pass
✓ Simple

This approach provides an efficient solution for plus one.

⏱ Time O(n) Single pass 💾 Space O(1) Minimal storage
plus_one_math.py
# Python Solution
# Problem: plus-one
# Approach: math
# Implementation placeholder for plus_one_math
# This file is auto-generated and should contain the solution code.
def plus_one_math():
pass
if __name__ == "__main__":
pass