0
0
Kotlinprogramming~5 mins

Secondary constructors in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Secondary constructors
O(n)
Understanding Time Complexity

Let's see how the time it takes to run code with secondary constructors changes as we create more objects.

We want to know how the number of objects affects the work done during construction.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

class Person {
    var name: String
    var age: Int

    constructor(name: String) {
        this.name = name
        this.age = 0
    }

    constructor(name: String, age: Int) {
        this.name = name
        this.age = age
    }
}

fun createPeople(n: Int): List {
    val list = mutableListOf()
    for (i in 1..n) {
        list.add(Person("Person $i", i))
    }
    return list
}

This code defines a class with two ways to create objects and then makes a list of many such objects.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop that creates and adds each Person object to the list.
  • How many times: Exactly n times, once for each Person created.
How Execution Grows With Input

Each new person means one more object created and added to the list.

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

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

Final Time Complexity

Time Complexity: O(n)

This means if you double the number of people, the time to create them roughly doubles too.

Common Mistake

[X] Wrong: "Secondary constructors make object creation slower in a way that changes time complexity."

[OK] Correct: Secondary constructors just offer different ways to build objects, but creating each object still takes constant time, so total time grows linearly with the number of objects.

Interview Connect

Understanding how object creation scales helps you explain performance clearly and shows you know how constructors affect program speed.

Self-Check

What if we added a loop inside the constructor that runs m times? How would the time complexity change?