Default arguments in Python - Time & Space Complexity
When using default arguments in functions, it's important to see how they affect the work done each time the function runs.
We want to know if having default values changes how long the function takes as input grows.
Analyze the time complexity of the following code snippet.
def greet(name, times=1):
for _ in range(times):
print(f"Hello, {name}!")
# Calling the function
# greet("Alice") # uses default times=1
# greet("Bob", 3) # times=3
This function prints a greeting message a number of times, using a default value if no number is given.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that prints the greeting.
- How many times: It runs exactly
timestimes, which can be the default or a given number.
Each time the function runs, the number of print operations grows with the times value.
| Input Size (times) | Approx. Operations |
|---|---|
| 1 | 1 print |
| 10 | 10 prints |
| 100 | 100 prints |
Pattern observation: The work grows directly with the number of times the loop runs.
Time Complexity: O(times)
This means the time taken grows in a straight line with how many times we want to print the greeting.
[X] Wrong: "Using default arguments makes the function run faster or slower depending on the default value."
[OK] Correct: The default value just sets a starting number; the function's time depends on the actual number used when called, not on whether it was default or given.
Understanding how default arguments affect loops helps you explain how your code behaves with different inputs, a skill that shows clear thinking in interviews.
"What if the function called another function inside the loop? How would that change the time complexity?"