Writing first Go program - Time & Space Complexity
When we write our first Go program, it is important to see how the program's steps grow as we add more work.
We want to know how the time to run changes when the program handles more data or tasks.
Analyze the time complexity of the following code snippet.
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
This code prints a simple greeting message once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Printing a message once.
- How many times: Exactly one time.
Since the program prints only once, the work does not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The number of steps stays the same no matter how big the input is.
Time Complexity: O(1)
This means the program takes the same amount of time no matter how much data it might handle.
[X] Wrong: "Printing a message once takes longer if the program is bigger."
[OK] Correct: The program only prints once, so the size of the program or input does not change the time it takes.
Understanding simple programs helps build confidence and shows you can think about how programs grow in time.
"What if we added a loop to print the message multiple times? How would the time complexity change?"