-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathproblem 17 in python
More file actions
26 lines (20 loc) · 1.31 KB
/
problem 17 in python
File metadata and controls
26 lines (20 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Intutuion:-
1. Traverse the array from the last digit**: Start from the least significant digit (last element) and try to add 1.
2. Handle Carry Over:
- If adding 1 to the current digit results in a value less than 10, update the digit and return the array immediately, as there’s no carry to propagate.
- If adding 1 results in 10, set the current digit to 0 and move to the next digit (to the left), carrying over the 1.
3. Handle Overflow:
- If all digits are processed and each resulted in a carry (e.g., `[9, 9, 9]`), prepend `1` to the array. This scenario happens if the input is entirely made up of `9`s.
This approach has a time complexity of \( O(N) \), as we are processing each digit once, and the space complexity is \( O(1) \) since we modify the array in place (except for the return value).
Here’s the Python code implementing the solution:
def increment(N, arr):
# Traverse the array from the last digit
for i in range(N - 1, -1, -1):
# If the current digit is less than 9, just increment it and return the array
if arr[i] < 9:
arr[i] += 1
return arr
# If the digit is 9, it becomes 0 and we carry over
arr[i] = 0
# If we finished the loop, it means all digits were 9, so we need to add a 1 at the start
return [1] + arr