Operator precedence in Go - Time & Space Complexity
When we write expressions with many operators, the order in which they run affects how many steps the program takes.
We want to see how the number of operations grows depending on how the operators are grouped.
Analyze the time complexity of the following code snippet.
func calculate(n int) int {
result := 0
for i := 0; i < n; i++ {
result += i*2 + 3
}
return result
}
This code runs a loop n times and uses operators inside the loop to calculate a value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs n times.
- How many times: Each iteration does a few simple math operations (multiplication, addition).
Each time n grows, the loop runs more times, doing the same small set of operations each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times the small math steps |
| 100 | About 100 times the small math steps |
| 1000 | About 1000 times the small math steps |
Pattern observation: The total steps grow directly with n, because the loop runs once per input size.
Time Complexity: O(n)
This means the time it takes grows in a straight line as the input number n gets bigger.
[X] Wrong: "Operator precedence changes how many times the loop runs or how many operations happen overall."
[OK] Correct: Operator precedence only changes the order of operations inside each loop step, not how many times the loop runs or the total steps.
Understanding how operator precedence affects the order of operations helps you reason about code clearly, which is a valuable skill in any coding challenge or real project.
"What if we added another nested loop inside the existing loop? How would the time complexity change?"