Increment and decrement in Go - Time & Space Complexity
Increment and decrement operations change a value by one step. We want to see how these operations affect the time it takes to run a program.
How does the number of increments or decrements grow when we repeat them many times?
Analyze the time complexity of the following code snippet.
package main
func countUp(n int) int {
total := 0
for i := 0; i < n; i++ {
total++
}
return total
}
This code counts up from zero to n by adding one each time in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Incrementing the variable
totalinside the loop. - How many times: Exactly
ntimes, once per loop cycle.
Each time we increase n, the loop runs that many times, doing one increment each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments |
| 100 | 100 increments |
| 1000 | 1000 increments |
Pattern observation: The number of increments grows directly with n. Double n, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the size of n.
[X] Wrong: "Incrementing inside a loop is always very fast, so it doesn't affect time much."
[OK] Correct: Even simple increments add up when repeated many times, so the total time depends on how many increments happen.
Understanding how simple steps like increments add up helps you explain how loops affect program speed. This skill shows you can think about how code grows with input size.
"What if we replaced the increment total++ with a function call inside the loop? How would the time complexity change?"