Returning errors in Go - Time & Space Complexity
When a Go function returns errors, it often checks conditions to decide if an error happened.
We want to see how these checks affect how long the function takes as input grows.
Analyze the time complexity of the following code snippet.
func findValue(arr []int, target int) (int, error) {
for i, v := range arr {
if v == target {
return i, nil
}
}
return -1, fmt.Errorf("value not found")
}
This function searches an array for a target value and returns an error if not found.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array elements one by one.
- How many times: Up to the length of the array, until the target is found or the end is reached.
As the array gets bigger, the function may check more elements before returning.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows roughly in direct proportion to the array size.
Time Complexity: O(n)
This means the time to find the value grows linearly with the size of the input array.
[X] Wrong: "Returning an error immediately makes the function run faster always."
[OK] Correct: Returning early only helps if the target is found early; if not, the function still checks many elements.
Understanding how error returns affect loops helps you explain your code's efficiency clearly and confidently.
"What if we changed the array to a sorted list and used binary search? How would the time complexity change?"