0
0
Goprogramming~5 mins

Basic input concepts in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Basic input concepts
O(n)
Understanding Time Complexity

When we read input in a program, the time it takes depends on how much data we get.

We want to see how the program's work grows as the input size grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	line, _ := reader.ReadString('\n')
	fmt.Println(line)
}

This code reads one line of input from the user and prints it back.

Identify Repeating Operations
  • Primary operation: Reading characters one by one until a newline is found.
  • How many times: As many characters as the input line length.
How Execution Grows With Input

As the input line gets longer, the program reads more characters, so it takes more time.

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

Pattern observation: The work grows directly with the input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to read input grows in a straight line with how many characters you type.

Common Mistake

[X] Wrong: "Reading input always takes the same time no matter how much data there is."

[OK] Correct: The program reads each character one by one, so more characters mean more time.

Interview Connect

Understanding how input size affects reading time helps you explain program speed clearly and shows you think about efficiency.

Self-Check

"What if we read multiple lines instead of one? How would the time complexity change?"