Skip to content
LEETFLIX

Easy · plus one with carry. Real solution for this problem — same player as the hand-authored deep-dives.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 66. Plus One. The copyrighted prompt is on LeetCode. This page is a working plus one with carry for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

digits =
[1, 2, 3]

Output

[1, 2, 4]

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Add one from the right

Walk from the last digit. A 9 becomes 0 and the carry keeps going; anything else increments and we stop. A leftover carry prepends 1.

Same addition-on-paper as Add Two Numbers, but the addend is always 1.

Algorithm

  1. From the right, if the digit is 9 set it to 0 and continue.
  2. Otherwise increment and return.
  3. If every digit was 9, prepend 1.
Time
O(n)
Space
O(1)
Solution.py
class Solution:    def plusOne(self, digits: list[int]) -> list[int]:        out = digits[:]        for i in range(len(out) - 1, -1, -1):            if out[i] < 9:                out[i] += 1                return out            out[i] = 0        return [1] + out
Watch this run

03

Interactive walkthrough

Playing “Add one from the right”. Edit the input, hit Run, then scrub.

Approach: Add one from the right

Loading animation…