703321. Fill array with 1's
Medium
Fill Array with 1's
Summary
Given an array of integers, fill it with 1's. This problem is about manipulating arrays and has no specific tags indicating dynamic programming or trees, so we can assume a general algorithmic problem.
Detailed Explanation
The approach to solve this problem involves iterating through the array and assigning each element a value of 1. The step-by-step breakdown of the solution is as follows:
- Initialize an integer variable
nwith the length of the input array. - Create a loop that runs from
0ton-1. - Inside the loop, assign the value
1to each element in the array at indexi, whereiis the current iteration. - After the loop finishes, return the filled array.
The time complexity of this solution is O(n), where n is the length of the input array, as we are performing a single pass through the array. The space complexity is also O(1) because we only use a constant amount of space to store the array and variable n.
Here's an ASCII art diagram showing the filled array:
[1, 1, 1, ..., 1]
Optimized Solutions
Java
public int[] fillArrayWithOnes(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = 1;
}
return arr;
}