Plus One in Python

The Plus One problem involves incrementing a large number represented as an array of digits. Given an array like [5, 3, 2, 4] representing 5324, we need to add 1 and return [5, 3, 2, 5] representing 5325.

Method 1: String Conversion Approach

Convert the array to a string, then to integer, add 1, and convert back to array ?

def plus_one_string(digits):
    # Convert digits to string
    num_str = ""
    for digit in digits:
        num_str += str(digit)
    
    # Convert to int, add 1, convert back to string
    num = int(num_str) + 1
    
    # Convert each character back to int and store in list
    result = []
    for char in str(num):
        result.append(int(char))
    
    return result

# Test the function
digits = [5, 3, 2, 4]
print(plus_one_string(digits))
[5, 3, 2, 5]

Method 2: Mathematical Approach (More Efficient)

Handle the addition digit by digit from right to left, managing carry operations ?

def plus_one_math(digits):
    # Start from the rightmost digit
    for i in range(len(digits) - 1, -1, -1):
        # If current digit is less than 9, just add 1 and return
        if digits[i] < 9:
            digits[i] += 1
            return digits
        # If current digit is 9, set it to 0 and continue
        digits[i] = 0
    
    # If we reach here, all digits were 9
    # Need to add 1 at the beginning
    return [1] + digits

# Test with normal case
digits1 = [5, 3, 2, 4]
print("Normal case:", plus_one_math(digits1.copy()))

# Test with carry case
digits2 = [9, 9, 9]
print("All 9s case:", plus_one_math(digits2.copy()))
Normal case: [5, 3, 2, 5]
All 9s case: [1, 0, 0, 0]

Edge Cases

The mathematical approach handles edge cases like [9, 9, 9] becoming [1, 0, 0, 0] ?

# Test various edge cases
test_cases = [
    [1, 2, 3],    # Normal case
    [9],          # Single digit 9
    [1, 9],       # Carry in middle
    [9, 9, 9]     # All 9s
]

for case in test_cases:
    result = plus_one_math(case.copy())
    print(f"{case} + 1 = {result}")
[1, 2, 3] + 1 = [1, 2, 4]
[9] + 1 = [1, 0]
[1, 9] + 1 = [2, 0]
[9, 9, 9] + 1 = [1, 0, 0, 0]

Comparison

Method Time Complexity Space Complexity Best For
String Conversion O(n) O(n) Simple implementation
Mathematical O(n) O(1) Memory efficient

Conclusion

The mathematical approach is more efficient as it handles carry operations in-place without string conversions. It elegantly manages edge cases like arrays of all 9s by prepending 1 to the result array.

Updated on: 2026-03-25T07:09:31+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements