Best practices in Java - Time & Space Complexity
When writing Java code, following best practices helps keep programs efficient and easy to understand.
We want to see how these practices affect how long the program takes to run as input grows.
Analyze the time complexity of the following Java method that finds the maximum number in an array.
public int findMax(int[] numbers) {
int max = numbers[0];
for (int num : numbers) {
if (num > max) {
max = num;
}
}
return max;
}
This method looks through all numbers once to find the largest value.
Look for loops or repeated steps.
- Primary operation: The for-each loop that checks each number.
- How many times: Once for every number in the input array.
As the list of numbers gets bigger, the method checks more items one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of checks grows directly with the input size.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input gets bigger.
[X] Wrong: "Adding more code inside the loop doesn't change the overall time complexity."
[OK] Correct: Even small extra steps inside the loop add up and can slow the program, especially with large inputs.
Understanding how your code grows with input size shows you can write clear and efficient programs, a skill valued in many coding challenges.
"What if we used two nested loops to compare every number with every other number? How would the time complexity change?"