Array declaration and initialization in Java - Time & Space Complexity
When we create and fill an array, it takes some time depending on how many items we add.
We want to know how the time needed grows as the array gets bigger.
Analyze the time complexity of the following code snippet.
int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i * 2;
}
This code creates an array of 5 integers and fills it with values by doubling the index.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that assigns values to each array element.
- How many times: It runs once for each element in the array, so 5 times here.
As the array size grows, the number of assignments grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 assignments |
| 100 | 100 assignments |
| 1000 | 1000 assignments |
Pattern observation: The time grows directly with the number of elements. Double the elements, double the work.
Time Complexity: O(n)
This means the time to fill the array grows in a straight line with the number of items.
[X] Wrong: "Creating an array is instant and does not depend on size."
[OK] Correct: While declaring an array reserves space quickly, initializing each element takes time that grows with the array size.
Understanding how array initialization time grows helps you explain performance clearly and shows you know how data structures work under the hood.
"What if we initialize the array with a fixed value instead of computing each element? How would the time complexity change?"
