0
0
Kotlinprogramming~5 mins

Data classes for value holders in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Data classes for value holders
O(n)
Understanding Time Complexity

Let's see how using data classes to hold values affects the time it takes to run code.

We want to know how the program's work grows when we create many data class objects.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    data class Point(val x: Int, val y: Int)

    fun createPoints(n: Int): List {
        val points = mutableListOf()
        for (i in 0 until n) {
            points.add(Point(i, i * 2))
        }
        return points
    }
    

This code creates a list of n Point objects, each holding two numbers.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Creating and adding a Point object inside a loop.
  • How many times: Exactly n times, once per loop iteration.
How Execution Grows With Input

Each time we increase n, we do more work creating and storing points.

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

Pattern observation: The work grows directly with n. Double the input, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to create points grows in a straight line with the number of points.

Common Mistake

[X] Wrong: "Creating data class objects is instant and doesn't add to time."

[OK] Correct: Each object creation takes time, so more objects mean more total time.

Interview Connect

Understanding how creating many simple objects affects time helps you explain performance clearly in interviews.

Self-Check

"What if we changed the loop to create points only for even numbers? How would the time complexity change?"