0
0
Kotlinprogramming~5 mins

Primary constructor and init blocks in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Primary constructor and init blocks
O(n)
Understanding Time Complexity

We want to understand how the time it takes to create an object grows when using primary constructors and init blocks in Kotlin.

How does the number of steps change as we add more properties or logic inside the init block?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

class Person(val name: String, val age: Int) {
    init {
        println("Creating person: $name, age $age")
    }
}

fun main() {
    val people = List(1000) { Person("Name$it", it) }
}

This code creates 1000 Person objects using a primary constructor and an init block that prints a message for each object.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Creating each Person object and running its init block.
  • How many times: The init block runs once per object, so 1000 times in this example.
How Execution Grows With Input

Each new object requires running the constructor and init block once, so the total steps grow directly with the number of objects.

Input Size (n)Approx. Operations
1010 constructor + 10 init calls = 20 steps
100100 constructor + 100 init calls = 200 steps
10001000 constructor + 1000 init calls = 2000 steps

Pattern observation: The total work doubles the input size because each object triggers one constructor and one init block call.

Final Time Complexity

Time Complexity: O(n)

This means the time to create objects grows linearly with the number of objects created.

Common Mistake

[X] Wrong: "The init block runs only once no matter how many objects are created."

[OK] Correct: Each object creation triggers its own init block, so it runs once per object, not just once total.

Interview Connect

Understanding how constructors and init blocks affect performance helps you write efficient Kotlin classes and shows you can reason about object creation costs.

Self-Check

"What if the init block contained a loop that runs m times? How would the time complexity change with respect to n and m?"