#66
Plus One
EasyArrayMathArrayMath
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution directly manipulates the array without converting it to an integer. It handles the carry from the least significant digit to the most significant efficiently, which is crucial for large numbers.
⚙️
Algorithm
4 steps- 1Step 1: Start from the last digit of the array.
- 2Step 2: Increment the last digit by one.
- 3Step 3: If the result is 10, set the current digit to 0 and move to the next digit to the left, adding the carry.
- 4Step 4: If there's still a carry after processing all digits, insert 1 at the beginning of the array.
solution.py7 lines
1def plus_one(digits):
2 for i in range(len(digits) - 1, -1, -1):
3 if digits[i] < 9:
4 digits[i] += 1
5 return digits
6 digits[i] = 0
7 return [1] + digitsℹ
Complexity note: The time complexity is O(n) because we may need to traverse the entire array in the worst case (e.g., when all digits are 9). The space complexity is O(1) since we are modifying the input array in place.
- 1Direct manipulation of the array avoids unnecessary conversions.
- 2Handling carry is crucial for correct results.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.