702664. Adding One
Easy
Adding One
Summary
The "Adding One" problem is a classic array manipulation challenge that requires us to modify an array in a specific way. Given an integer array, our goal is to add one to all elements in the array while maintaining the original order and preserving any existing duplicates. This problem involves basic concepts of arrays and data structures.
Detailed Explanation
To solve this problem, we'll follow these steps:
- Iterate through the input array.
- For each element, increment it by 1.
- Store the modified elements in a new array to preserve the original order.
Here's a step-by-step breakdown of the solution:
input = [1, 2, 3, 4]
result = []
for num in input:
result.append(num + 1)
print(result) # Output: [2, 3, 4, 5]
Time complexity analysis:
- Iterating through the array takes O(n) time, where n is the length of the array.
- Modifying each element and storing it in a new array also takes O(n) time.
Space complexity analysis:
- We're creating a new array to store the modified elements, which takes O(n) space.
Optimized Solutions
Java
public int[] addOne(int[] arr) {
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = arr[i] + 1;
}
return result;
}