Using Scanner class in Java - Time & Space Complexity
When we use the Scanner class to read input, it is important to understand how the time taken grows as the input size increases.
We want to know how the program's running time changes when we read more data.
Analyze the time complexity of the following code snippet.
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
int value = scanner.nextInt();
System.out.println(value);
}
scanner.close();
}
}
This code reads an integer n, then reads n more integers and prints each one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading an integer inside the loop using scanner.nextInt()
- How many times: Exactly n times, where n is the first input read
As the number n grows, the number of times we read input and print also grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 reads and prints |
| 100 | About 100 reads and prints |
| 1000 | About 1000 reads and prints |
Pattern observation: The work grows directly in proportion to n; doubling n doubles the work.
Time Complexity: O(n)
This means the time taken grows in a straight line with the number of inputs read.
[X] Wrong: "Reading input with Scanner is always constant time regardless of input size."
[OK] Correct: Each call to scanner.nextInt() reads one integer, so more inputs mean more calls and more time.
Understanding how input reading scales helps you write efficient programs and shows you can think about performance in real situations.
"What if we changed the code to read all inputs into an array first, then process them? How would the time complexity change?"