Parameters with default values in Kotlin - Time & Space Complexity
We want to see how the time it takes to run a function changes when it has parameters with default values.
Does using default values affect how long the function takes as input grows?
Analyze the time complexity of the following code snippet.
fun greet(name: String = "Guest", times: Int = 1) {
for (i in 1..times) {
println("Hello, $name!")
}
}
fun main() {
greet()
greet("Alice", 3)
}
This function prints a greeting message a number of times, using default values if no arguments are given.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that prints the greeting message.
- How many times: It runs exactly
timestimes, which depends on the input parameter.
The number of greetings printed grows directly with the times parameter.
| Input Size (times) | Approx. Operations |
|---|---|
| 1 | 1 print operation |
| 3 | 3 print operations |
| 100 | 100 print operations |
Pattern observation: The work grows in a straight line as times increases.
Time Complexity: O(n)
This means the time to run the function grows directly with the number of times it prints the message.
[X] Wrong: "Using default values makes the function run faster or slower depending on the defaults."
[OK] Correct: Default values only fill in missing arguments; they do not change how many times the loop runs. The time depends on the actual times value used.
Understanding how default parameters affect performance helps you explain your code clearly and shows you think about how input size impacts work done.
What if we changed the loop to run from 1 to times * 2? How would the time complexity change?