</>

66. Plus One

Easy NeetCode 150
Math & Geometry Time O(N) Space O(1)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Math & Geometry
Time
O(N)
Space
O(1)

Standard Solution (C++)

SummaryGiven an integer represented as a vector of decimal digits, return the vector that represents the integer incremented by one.

Approach
  • Traverse the digits from least significant (rightmost) to most significant (leftmost).
  • Increment the current digit; if it does not overflow (i.e., it stays below 10), return immediately — no carry propagates further.
  • If the digit wraps to 10, set it to 0 and continue left, propagating the carry.
  • If the loop finishes without an early return, every digit was 9 (e.g., 999 → 1000), so prepend a 1 to the array.
#include <vector>
using namespace std;

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        // Walk from the least-significant digit toward the most-significant.
        for (int i = static_cast<int>(digits.size()) - 1; i >= 0; --i) {
            if (digits[i] < 9) {
                // No carry will propagate; increment and we're done.
                ++digits[i];
                return digits;
            }
            // Current digit is 9: it becomes 0 and the carry moves left.
            digits[i] = 0;
        }
        // All digits were 9 (e.g. 999 -> 1000): prepend the leading 1.
        digits.insert(digits.begin(), 1);
        return digits;
    }
};
Time O(n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        for(int i=digits.size()-1; i>=0; --i){
            ++digits[i];
            if(digits[i]<10){
                return digits; 
            }
            digits[i]=0;
        } 
        digits.insert(digits.begin(), 1);
        return digits;
    }
};

// Time Complexity: O(N)
// Space Complexity: O(1)
Time O(N) Space O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern