0
0
Goprogramming~5 mins

Package scope rules in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Package scope rules
O(n)
Understanding Time Complexity

When we write Go code, variables and functions can be visible in different places. Package scope means they are visible throughout the whole package.

We want to understand how this visibility affects how often code runs and how that grows with input size.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


package main

import "fmt"

var count int // package scope variable

func increment(n int) {
    for i := 0; i < n; i++ {
        count++
    }
}

func main() {
    increment(1000)
    fmt.Println(count)
}
    

This code uses a package-level variable count that the increment function updates in a loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop inside increment that runs n times.
  • How many times: Exactly n times, where n is the input to increment.
How Execution Grows With Input

As n grows, the number of times the loop runs grows the same way.

Input Size (n)Approx. Operations
1010 increments of count
100100 increments of count
10001000 increments of count

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

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the input size.

Common Mistake

[X] Wrong: "Because count is package scoped, the loop runs multiple times automatically."

[OK] Correct: Package scope only means the variable is visible everywhere in the package. It does not cause the loop to run more times. The loop runs exactly as many times as coded.

Interview Connect

Understanding how package scope affects code visibility helps you reason about how often code runs and where variables change. This skill is useful when explaining code behavior clearly.

Self-Check

What if the increment function called itself recursively instead of using a loop? How would the time complexity change?