0
0
Kotlinprogramming~5 mins

Parameters with default values in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Parameters with default values
O(n)
Understanding Time 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?

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that prints the greeting message.
  • How many times: It runs exactly times times, which depends on the input parameter.
How Execution Grows With Input

The number of greetings printed grows directly with the times parameter.

Input Size (times)Approx. Operations
11 print operation
33 print operations
100100 print operations

Pattern observation: The work grows in a straight line as times increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the function grows directly with the number of times it prints the message.

Common Mistake

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

Interview Connect

Understanding how default parameters affect performance helps you explain your code clearly and shows you think about how input size impacts work done.

Self-Check

What if we changed the loop to run from 1 to times * 2? How would the time complexity change?