Plus One Solution for Wipro
Company: Wipro · Difficulty: Easy · Topics: Array, Math
Problem Statement
You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order.
Increment the large integer by one and return the resulting array of digits.
Examples
Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123. Incrementing by 1 gives 123 + 1 = 124.
Example 2:
Input: digits = [9,9,9]
Output: [1,0,0,0]
Explanation: The array represents the integer 999. Incrementing by 1 gives 999 + 1 = 1000.
Approach
Right-to-Left Traversal (Optimal)
1. Start from the rightmost digit
2. If the digit is less than 9, increment it and return
3. If the digit is 9, set it to 0 and continue to the left
4. If all digits are 9, add a new digit 1 at the beginning
Time and Space Complexity
- Time Complexity: O(n) - Single pass through array (worst case)
- Space Complexity: O(1) - In-place modification (except when adding new digit)