0
0
Javaprogramming~5 mins

Using Scanner class in Java - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Using Scanner class
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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
How Execution Grows With Input

As the number n grows, the number of times we read input and print also grows linearly.

Input Size (n)Approx. Operations
10About 10 reads and prints
100About 100 reads and prints
1000About 1000 reads and prints

Pattern observation: The work grows directly in proportion to n; doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time taken grows in a straight line with the number of inputs read.

Common Mistake

[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.

Interview Connect

Understanding how input reading scales helps you write efficient programs and shows you can think about performance in real situations.

Self-Check

"What if we changed the code to read all inputs into an array first, then process them? How would the time complexity change?"