Problem Description
Given an array of digits representing a large integer (with the most significant digit at index 0), increment the number by one and return the resulting array of digits without any leading zeros.
Key Insights
- The digits are stored from most significant to least significant.
- Start processing from the least significant digit (end of array) to handle potential carry.
- Carefully handle the case where all digits are 9, in which case an additional digit is needed.
- Use an in-place update approach to reduce extra space usage when possible.
Space and Time Complexity
Time Complexity: O(n) in the worst-case, where n is the number of digits. Space Complexity: O(n) in the worst-case for the output array (when an extra digit is added).
Solution
We iterate from the end of the digits array towards the beginning, adding one to the current digit. If the digit becomes 10, we set it to 0 and propagate the carry to the next digit. If no carry is needed, we can return the result immediately. If we finish processing the array and still have a carry (e.g., the number was all 9s), we create a new array with one extra digit at the beginning set to 1.