Common array operations in Java - Time & Space Complexity
When working with arrays, it is important to know how the time to complete operations changes as the array grows.
We want to understand how fast or slow common array tasks run when the array size increases.
Analyze the time complexity of the following code snippet.
int[] arr = new int[n];
// Fill array with values
for (int i = 0; i < n; i++) {
arr[i] = i * 2;
}
// Search for a value
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
break;
}
}
This code fills an array with values and then searches for a target value by checking each element.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Two for-loops that each run through the array elements.
- How many times: Each loop runs up to n times, where n is the array size.
As the array size grows, the number of steps to fill and search grows roughly in proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 steps (10 to fill + up to 10 to search) |
| 100 | About 200 steps |
| 1000 | About 2000 steps |
Pattern observation: The total steps grow roughly twice as fast as the array size, which means the time grows linearly.
Time Complexity: O(n)
This means the time to complete these operations grows in direct proportion to the size of the array.
[X] Wrong: "Searching an array always takes the same time no matter how big it is."
[OK] Correct: Searching means checking elements one by one, so bigger arrays usually take more time.
Understanding how array operations scale helps you explain your code choices clearly and shows you know how to write efficient programs.
"What if we used a sorted array and binary search instead of a simple loop? How would the time complexity change?"
