0
0
Kotlinprogramming~5 mins

Interface declaration and implementation in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Interface declaration and implementation
O(n)
Understanding Time Complexity

When we use interfaces in Kotlin, we want to know how the program's speed changes as we add more code or objects that use these interfaces.

We ask: How does the time to run grow when we create and use many implementations of an interface?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

interface Greeter {
    fun greet()
}

class FriendlyGreeter : Greeter {
    override fun greet() {
        println("Hello!")
    }
}

fun greetAll(greeters: List) {
    for (greeter in greeters) {
        greeter.greet()
    }
}

This code defines an interface and a class that implements it. Then it calls the greet method on each object in a list.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the list of greeters and calling greet()
  • How many times: Once for each greeter in the list (n times)
How Execution Grows With Input

Each new greeter added means one more greet() call, so the total work grows evenly with the number of greeters.

Input Size (n)Approx. Operations
1010 greet() calls
100100 greet() calls
10001000 greet() calls

Pattern observation: The work grows in a straight line as we add more greeters.

Final Time Complexity

Time Complexity: O(n)

This means the time to greet everyone grows directly with the number of greeters.

Common Mistake

[X] Wrong: "Calling greet() on each object is constant time no matter how many objects there are."

[OK] Correct: Each greet() call happens once per object, so more objects mean more calls and more time.

Interview Connect

Understanding how loops over interface implementations scale helps you explain how your code handles many objects efficiently.

Self-Check

"What if greet() itself contained a loop over a list of messages? How would the time complexity change?"