0
0
Kotlinprogramming~5 mins

Companion object with interfaces in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Companion object with interfaces
O(n)
Understanding Time Complexity

Let's see how the time needed to run code with companion objects and interfaces changes as we use more data.

We want to know how the program's work grows when it calls interface methods inside a companion object.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

interface Greeter {
    fun greet(name: String): String
}

class Person {
    companion object : Greeter {
        override fun greet(name: String) = "Hello, $name!"
    }
}

fun greetAll(names: List) {
    for (name in names) {
        println(Person.greet(name))
    }
}

This code defines an interface and a companion object that implements it. It then greets each name in a list using the companion object.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the list of names and calling the greet method for each.
  • How many times: Once for each name in the input list.
How Execution Grows With Input

Each new name adds one more greeting call, so the work grows evenly with the list size.

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

Pattern observation: The number of operations grows directly with the number of names.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of names to greet.

Common Mistake

[X] Wrong: "Calling a method on a companion object with an interface makes the code slower for each call."

[OK] Correct: Each call runs in constant time; the interface and companion object do not add extra loops or repeated work per call.

Interview Connect

Understanding how companion objects and interfaces affect time helps you explain code design choices clearly and confidently.

Self-Check

"What if the greet method itself contained a loop over the input string's characters? How would the time complexity change?"