0
0
Goprogramming~5 mins

Method call behavior in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Method call behavior
O(n)
Understanding Time Complexity

When we call a method in Go, it runs some code. We want to know how the time it takes changes as the input grows.

How does calling a method affect the total work done by the program?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


package main

import "fmt"

type Counter struct {
    count int
}

func (c *Counter) Increment(n int) {
    for i := 0; i < n; i++ {
        c.count++
    }
}

func main() {
    c := Counter{}
    c.Increment(100)
    fmt.Println(c.count)
}
    

This code defines a method Increment that adds 1 to count n times. We call it with n = 100.

Identify Repeating Operations
  • Primary operation: The for loop inside the Increment method that runs c.count++ repeatedly.
  • How many times: The loop runs exactly n times, where n is the input to Increment.
How Execution Grows With Input

As n grows, the number of times we add to count grows the same way.

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

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

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Calling a method always takes the same time no matter what."

[OK] Correct: The method here has a loop that runs n times, so bigger n means more work and more time.

Interview Connect

Understanding how method calls affect time helps you explain your code clearly and shows you know what happens inside your functions.

Self-Check

"What if the Increment method called another method inside the loop? How would that change the time complexity?"