0
0
Kotlinprogramming~5 mins

Extension function syntax in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Extension function syntax
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run an extension function changes as the input grows.

How does adding an extension function affect the work done when called on different input sizes?

Scenario Under Consideration

Analyze the time complexity of the following Kotlin extension function.


fun List<Int>.sumElements(): Int {
    var sum = 0
    for (element in this) {
        sum += element
    }
    return sum
}

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5)
    println(numbers.sumElements())
}
    

This code adds a new function to List<Int> that sums all its elements.

Identify Repeating Operations

Look at what repeats when the function runs.

  • Primary operation: Looping through each element in the list.
  • How many times: Once for every item in the list.
How Execution Grows With Input

As the list gets bigger, the function does more work by adding more numbers.

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

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the list size.

Common Mistake

[X] Wrong: "Extension functions run instantly no matter the input size."

[OK] Correct: Even though the function is added outside the class, it still runs the code inside, which depends on the input size.

Interview Connect

Knowing how extension functions behave helps you explain your code clearly and understand performance when adding new features.

Self-Check

"What if the extension function called another function inside that also loops over the list? How would the time complexity change?"