0
0
Goprogramming~5 mins

Function execution flow in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Function execution flow
O(n)
Understanding Time Complexity

When we look at how a function runs, we want to know how long it takes as the input grows.

We ask: How does the work inside the function increase when input changes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

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

This function adds up all numbers in a list and returns the total.

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 every number in the list.
How Execution Grows With Input

As the list gets bigger, the function does more additions, one for each number.

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 with the input size.

Common Mistake

[X] Wrong: "The function runs in the same time no matter how many numbers there are."

[OK] Correct: Because the function must add each number, more numbers mean more work.

Interview Connect

Understanding how function steps grow with input helps you explain your code clearly and think about efficiency.

Self-Check

"What if we changed the function to sum only the first half of the list? How would the time complexity change?"