Assignment operators in Go - Time & Space Complexity
Assignment operators are used to store or update values in variables. We want to see how the time it takes to run code with assignment operators changes as the input size grows.
How does the number of assignments grow when we repeat them many times?
Analyze the time complexity of the following code snippet.
for i := 0; i < n; i++ {
x = i
}
This code assigns the value of i to x repeatedly in a loop that runs n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Assignment
x = iinside the loop. - How many times: Exactly
ntimes, once per loop iteration.
Each time the loop runs, one assignment happens. So if the input n grows, the number of assignments grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 assignments |
| 100 | 100 assignments |
| 1000 | 1000 assignments |
Pattern observation: The number of assignments grows directly with n. Double n, double the assignments.
Time Complexity: O(n)
This means the time to run the code grows in a straight line with the size of n. More input means more assignments.
[X] Wrong: "Assignment inside a loop is constant time because it's just one operation."
[OK] Correct: Even though one assignment is quick, doing it n times means the total time grows with n. So it's not constant overall.
Understanding how simple operations like assignments add up helps you explain how code runs as input grows. This skill shows you can think about efficiency clearly and simply.
"What if we added another nested loop inside that repeats the assignment? How would the time complexity change?"