0
0
Goprogramming~5 mins

Function parameters in Go - Time & Space Complexity

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

When we use function parameters, we want to know how the time to run the function changes as the input changes.

We ask: How does the size or number of parameters affect the work the function does?

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 the numbers given in a list and returns the total.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each number in the list.
  • How many times: Once for every number 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 number of items; double the items, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the number of input items.

Common Mistake

[X] Wrong: "Function parameters do not affect time because they are just inputs."

[OK] Correct: The size or amount of data passed as parameters can change how many steps the function takes, so it does affect time.

Interview Connect

Understanding how input size affects function time helps you explain your code clearly and shows you think about efficiency, a skill valued in real projects.

Self-Check

"What if the function took two lists instead of one? How would the time complexity change?"