0
0
Kotlinprogramming~5 mins

Factory pattern with companion objects in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Factory pattern with companion objects
O(n)
Understanding Time Complexity

We want to understand how the time it takes to create objects using a factory pattern with companion objects changes as we ask for more objects.

How does the number of objects requested affect the work done inside the factory?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Product private constructor(val name: String) {
    companion object Factory {
        fun create(name: String): Product {
            return Product(name)
        }
    }
}

fun createProducts(names: List): List {
    return names.map { Product.create(it) }
}
    

This code defines a Product class with a companion object factory method to create instances. The createProducts function makes a list of products from a list of names.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the factory method Product.create for each name.
  • How many times: Once for each element in the input list names.
How Execution Grows With Input

Each product creation takes about the same time, so total work grows as we add more names.

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

Pattern observation: The work grows directly with the number of names; doubling names doubles work.

Final Time Complexity

Time Complexity: O(n)

This means the time to create all products grows in a straight line with the number of products requested.

Common Mistake

[X] Wrong: "Using a companion object factory makes object creation instant or constant time regardless of how many objects we create."

[OK] Correct: Each call to the factory still creates a new object, so the total time grows with how many objects you make.

Interview Connect

Understanding how factory methods scale helps you explain design choices clearly and shows you think about efficiency, which is a valuable skill in real projects.

Self-Check

What if the factory method cached and reused existing objects instead of creating new ones? How would the time complexity change?