0
0
Kotlinprogramming~5 mins

Open classes and methods in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Open classes and methods
O(n)
Understanding Time Complexity

Let's see how the time it takes to run code changes when we use open classes and methods in Kotlin.

We want to know how calling open methods affects the work the program does as it runs.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

open class Animal {
    open fun makeSound() {
        println("Some sound")
    }
}

class Dog : Animal() {
    override fun makeSound() {
        println("Bark")
    }
}

fun playWithAnimals(animals: List) {
    for (animal in animals) {
        animal.makeSound()
    }
}

This code defines an open class and method, then calls the method on a list of animals.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the list of animals and calling makeSound() on each.
  • How many times: Once for each animal in the list (n times).
How Execution Grows With Input

Each animal in the list causes one call to makeSound(). So, if the list grows, the work grows the same way.

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

Pattern observation: The number of calls grows directly with the number of animals.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the number of animals increases.

Common Mistake

[X] Wrong: "Because methods are open and can be overridden, calling them is slower and changes the time complexity."

[OK] Correct: Overriding methods does not change how many times the method is called. The loop still runs once per item, so the overall time grows the same way.

Interview Connect

Understanding how method calls inside loops affect time helps you explain how your code scales. This skill shows you can think about performance clearly.

Self-Check

"What if the makeSound() method itself contained a loop over a list? How would that change the time complexity?"