Global keyword in Python - Time & Space Complexity
Let's explore how using the global keyword affects the time it takes for a program to run.
We want to see if accessing or changing global variables changes how long the program takes as it grows.
Analyze the time complexity of the following code snippet.
count = 0
def increment(n):
global count
for _ in range(n):
count += 1
increment(5)
This code increases a global variable by 1, n times inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs n times.
- How many times: Exactly n times, where n is the input number.
Each time n grows, the loop runs that many more times, increasing work linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments |
| 100 | 100 increments |
| 1000 | 1000 increments |
Pattern observation: The work grows directly with n; double n means double work.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input number n grows.
[X] Wrong: "Using the global keyword makes the loop slower or faster."
[OK] Correct: The global keyword only changes where the variable lives, not how many times the loop runs. The time depends on the loop count, not on global or local variables.
Understanding how global variables affect performance helps you write clear and efficient code, a skill valued in many coding challenges and real projects.
"What if we replaced the for-loop with a recursive function that increments the global variable? How would the time complexity change?"