Operator precedence in Kotlin - Time & Space Complexity
We want to see how the order of operations affects how many steps a program takes.
How does the way Kotlin decides which operation to do first change the work done?
Analyze the time complexity of the following code snippet.
fun calculate(values: List): Int {
var result = 0
for (v in values) {
result += v * 2 + 3
}
return result
}
This code multiplies each number by 2, adds 3, and sums all results.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list once.
- How many times: Exactly once for each item in the input list.
Each new number adds a fixed amount of work: multiply, add, then add to total.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times the fixed steps |
| 100 | About 100 times the fixed steps |
| 1000 | About 1000 times the fixed steps |
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 as the input list gets bigger.
[X] Wrong: "Changing the order of operations inside the loop changes how many times the loop runs."
[OK] Correct: The loop runs once per item no matter the order; operator precedence only changes how each item's calculation happens, not the number of times the loop runs.
Understanding how operator precedence affects calculations helps you explain how code runs step-by-step, a skill useful in many coding discussions.
"What if we added another loop inside the existing loop? How would the time complexity change?"