0
0
Kotlinprogramming~5 mins

Infix functions for readable calls in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Infix functions for readable calls
O(n)
Understanding Time Complexity

Let's see how the time cost changes when using infix functions in Kotlin.

We want to know how the program's work grows as input gets bigger.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    infix fun Int.times(str: String): String {
        return str.repeat(this)
    }

    fun main() {
        val result = 3 times "Hi"
        println(result)
    }
    

This code defines an infix function to repeat a string a number of times, then calls it.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The string repeat function internally repeats the string by concatenation.
  • How many times: It repeats the string exactly as many times as the integer value (here, 3 times).
How Execution Grows With Input

As the number of repeats grows, the work to build the final string grows too.

Input Size (n)Approx. Operations
10About 10 string concatenations
100About 100 string concatenations
1000About 1000 string concatenations

Pattern observation: The work grows roughly in direct proportion to the number of repeats.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows linearly with how many times the string is repeated.

Common Mistake

[X] Wrong: "Using an infix function makes the code faster or slower by itself."

[OK] Correct: The infix keyword only changes how we write the call, not how many steps the program takes.

Interview Connect

Understanding how function calls affect time helps you explain your code clearly and shows you think about efficiency.

Self-Check

"What if the infix function repeated the string twice as many times internally? How would the time complexity change?"