Return inside loops in Go - Time & Space Complexity
When a return statement is inside a loop, it can stop the loop early. This affects how long the code runs.
We want to see how the running time changes when the return happens inside the loop.
Analyze the time complexity of the following code snippet.
func findFirstEven(numbers []int) int {
for _, num := range numbers {
if num%2 == 0 {
return num
}
}
return -1
}
This function looks for the first even number in a list and returns it immediately when found.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of numbers.
- How many times: Up to the first even number found, or the whole list if none found.
The time depends on where the first even number is. If it is near the start, the loop stops quickly. If none are even, the loop checks every number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Between 1 and 10 checks |
| 100 | Between 1 and 100 checks |
| 1000 | Between 1 and 1000 checks |
Pattern observation: Best case is very fast, worst case grows linearly with input size.
Time Complexity: O(n)
This means in the worst case, the time grows directly with the number of items in the list.
[X] Wrong: "Because there is a return inside the loop, the time is always constant."
[OK] Correct: The return stops the loop early only if the condition is met quickly. If not, the loop runs through all items, so time depends on input size.
Understanding how return inside loops affects time helps you explain code efficiency clearly. It shows you can think about best and worst cases, a useful skill in real coding.
"What if the function returned the last even number instead of the first? How would the time complexity change?"