0
0
Goprogramming~5 mins

Basic data types in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Basic data types
O(n)
Understanding Time Complexity

When working with basic data types in Go, it's helpful to know how fast operations run.

We want to see how the time to do simple tasks changes as the input size grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


package main

func sumInts(numbers []int) int {
    total := 0
    for _, num := range numbers {
        total += num
    }
    return total
}

This code adds up all numbers in a list of integers.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Adding each number to total inside a loop.
  • How many times: Once for each number in the list.
How Execution Grows With Input

As the list gets longer, the time to add all numbers grows in a straight line.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the input list gets bigger.

Common Mistake

[X] Wrong: "Adding numbers is always instant, no matter how many there are."

[OK] Correct: Even simple addition takes time, and doing it many times adds up as the list grows.

Interview Connect

Understanding how basic operations scale helps you explain code efficiency clearly and confidently.

Self-Check

"What if we changed the list to a fixed size array? How would the time complexity change?"