0
0
Goprogramming~5 mins

Test-driven basics in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Test-driven basics
O(n)
Understanding Time Complexity

When writing tests first, it is important to know how the time your tests take grows as your code runs on bigger inputs.

We want to see how the test and code execution time changes when input size changes.

Scenario Under Consideration

Analyze the time complexity of the following test-driven code snippet.


func Sum(nums []int) int {
    total := 0
    for _, n := range nums {
        total += n
    }
    return total
}

func TestSum(t *testing.T) {
    result := Sum([]int{1, 2, 3, 4})
    if result != 10 {
        t.Errorf("Expected 10, got %d", result)
    }
}
    

This code defines a function that adds numbers in a list and a test that checks if it works correctly.

Identify Repeating Operations

Look for loops or repeated steps in the code.

  • Primary operation: Looping through each number in the input list to add it.
  • How many times: Once for each number in the list.
How Execution Grows With Input

As the list gets bigger, the time to add all numbers grows in a straight line.

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

Pattern observation: Doubling the input doubles the work because each number is added once.

Final Time Complexity

Time Complexity: O(n)

This means the time grows directly with the number of items you add.

Common Mistake

[X] Wrong: "The test time stays the same no matter how many numbers I add."

[OK] Correct: The test runs the function, and the function adds each number, so more numbers mean more work and more time.

Interview Connect

Understanding how test and code time grows helps you write better tests and code that work well even with bigger inputs.

Self-Check

"What if the Sum function used recursion instead of a loop? How would the time complexity change?"