Use cases in Java - Time & Space Complexity
When we look at use cases in Java, we want to understand how the time it takes to run changes as the input grows.
We ask: How does the program's work increase when we give it more data?
Analyze the time complexity of the following code snippet.
public void printAllPairs(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers.length; j++) {
System.out.println(numbers[i] + ", " + numbers[j]);
}
}
}
This code prints every possible pair of numbers from the input array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops printing pairs.
- How many times: Outer loop runs n times; inner loop runs n times for each outer loop.
As the input size grows, the number of pairs grows much faster.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 100 |
| 100 | 10,000 |
| 1000 | 1,000,000 |
Pattern observation: Doubling the input size makes the work about four times bigger.
Time Complexity: O(n²)
This means the work grows quickly as input grows, because every item pairs with every other item.
[X] Wrong: "Since there are two loops, the time is just twice as long as input size."
[OK] Correct: The loops are nested, so the inner loop runs completely for each outer loop step, multiplying work, not just adding.
Understanding how nested loops affect time helps you explain your code clearly and shows you can think about efficiency in real projects.
"What if we replaced the inner loop to run only half the array length? How would the time complexity change?"
