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?"
Practice
Solution
Step 1: Understand Java array declaration syntax
In Java, arrays are declared with the type followed by square brackets, then the variable name, and initialized with 'new' and size.Step 2: Check each option for correct syntax
int[] numbers = new int[5]; uses correct syntax: int[] numbers = new int[5]; Options A, B, and D have syntax errors or missing parts.Final Answer:
int[] numbers = new int[5]; -> Option DQuick Check:
Correct array declaration = int[] numbers = new int[5]; [OK]
- Missing square brackets after type
- Not using 'new' keyword
- Incorrect variable initialization
arr in Java?Solution
Step 1: Recall Java array indexing
Java arrays use zero-based indexing, so the first element is at index 0, second at 1, third at 2.Step 2: Identify correct syntax for accessing elements
Elements are accessed with square brackets []. So arr[2] accesses the third element. Options A and D use incorrect syntax, and C accesses the fourth element.Final Answer:
arr[2]; -> Option BQuick Check:
Third element index = 2 [OK]
- Using parentheses instead of brackets
- Using 1-based indexing
- Trying to use methods like get() on arrays
int[] nums = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
}
System.out.println(sum);Solution
Step 1: Understand the array and loop
The array nums contains 1, 2, 3, 4, 5. The loop runs from i=0 to i=4 (nums.length is 5).Step 2: Calculate the sum of all elements
sum = 0 + 1 + 2 + 3 + 4 + 5 = 15.Final Answer:
15 -> Option AQuick Check:
Sum of 1 to 5 = 15 [OK]
- Off-by-one error in loop
- Starting sum at wrong value
- Using wrong loop condition
data, but it causes a runtime error. What is the error?int[] data = {10, 20, 30};
for (int i = 1; i <= data.length; i++) {
System.out.println(data[i]);
}Solution
Step 1: Analyze loop indices and array length
The array has length 3, valid indices are 0, 1, 2. The loop runs i from 1 to 3 inclusive.Step 2: Identify index causing error
When i = 3, data[3] is accessed, which is out of bounds and causes ArrayIndexOutOfBoundsException.Final Answer:
ArrayIndexOutOfBoundsException because loop goes beyond last index -> Option AQuick Check:
Loop index must be less than length [OK]
- Using <= instead of < in loop condition
- Starting loop at 1 instead of 0
- Ignoring zero-based indexing
arr, which code snippet correctly counts how many elements are greater than 10?Solution
Step 1: Understand the counting condition
We want to count elements strictly greater than 10, so condition is arr[i] > 10.Step 2: Check loop indices and condition correctness
int count = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] > 10) { count++; } } System.out.println(count); uses correct zero-based indexing and correct condition. int count = 0; for (int i = 1; i <= arr.length; i++) { if (arr[i] > 10) { count++; } } System.out.println(count); has out-of-bounds error. int count = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] >= 10) { count++; } } System.out.println(count); counts elements >= 10 (includes 10). int count = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] < 10) { count++; } } System.out.println(count); counts elements less than 10, which is wrong.Final Answer:
int count = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] > 10) { count++; } } System.out.println(count); -> Option CQuick Check:
Count elements with arr[i] > 10 using correct loop [OK]
- Using <= instead of < in loop
- Using wrong comparison operator
- Starting loop at 1 causing index errors
Ready to prove it?
Pass the test and this pattern moves unknown
