0
0
Goprogramming~5 mins

Return values in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Return values
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code with return values changes as the input grows.

Specifically, how does returning values affect the work done by the program?

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

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each number in the list once.
  • How many times: Exactly once for each item in the input 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 size of the input list.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Returning a value makes the function run slower by a lot."

[OK] Correct: Returning a single value at the end is very fast and does not add extra loops or big work.

Interview Connect

Understanding how return values fit into time complexity helps you explain your code clearly and confidently in interviews.

Self-Check

"What if the function returned a list of all partial sums instead of a single total? How would the time complexity change?"