0
0
Pythonprogramming~5 mins

Global keyword in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Global keyword
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each time n grows, the loop runs that many more times, increasing work linearly.

Input Size (n)Approx. Operations
1010 increments
100100 increments
10001000 increments

Pattern observation: The work grows directly with n; double n means double work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the input number n grows.

Common Mistake

[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.

Interview Connect

Understanding how global variables affect performance helps you write clear and efficient code, a skill valued in many coding challenges and real projects.

Self-Check

"What if we replaced the for-loop with a recursive function that increments the global variable? How would the time complexity change?"