Basic input concepts in Go - Time & Space 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.
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.
- Primary operation: Reading characters one by one until a newline is found.
- How many times: As many characters as the input line length.
As the input line gets longer, the program reads more characters, so it takes more time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 character reads |
| 100 | About 100 character reads |
| 1000 | About 1000 character reads |
Pattern observation: The work grows directly with the input size.
Time Complexity: O(n)
This means the time to read input grows in a straight line with how many characters you type.
[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.
Understanding how input size affects reading time helps you explain program speed clearly and shows you think about efficiency.
"What if we read multiple lines instead of one? How would the time complexity change?"