0
0
Goprogramming~5 mins

Writing first Go program - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Writing first Go program
O(1)
Understanding Time 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.

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Printing a message once.
  • How many times: Exactly one time.
How Execution Grows With Input

Since the program prints only once, the work does not grow with input size.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The number of steps stays the same no matter how big the input is.

Final Time Complexity

Time Complexity: O(1)

This means the program takes the same amount of time no matter how much data it might handle.

Common Mistake

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

Interview Connect

Understanding simple programs helps build confidence and shows you can think about how programs grow in time.

Self-Check

"What if we added a loop to print the message multiple times? How would the time complexity change?"