Program stability concepts in Go - Time & Space Complexity
Program stability means how well a program keeps working correctly as input size changes.
We want to know how the program's speed changes when it handles more data.
Analyze the time complexity of the following code snippet.
func stableProcess(data []int) int {
result := 0
for _, value := range data {
if value%2 == 0 {
result += value
}
}
return result
}
This code sums all even numbers in a list of integers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the data list.
- How many times: Once for every item in the list.
As the list gets bigger, the program checks more numbers one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "The program runs faster because it only adds even numbers."
[OK] Correct: The program still checks every number, so the time depends on the total list size, not just the even numbers.
Understanding how a program's speed changes with input size shows you can write stable and predictable code.
"What if we changed the code to sum only numbers greater than 100? How would the time complexity change?"