0
0
Kotlinprogramming~5 mins

Set creation (setOf, mutableSetOf) in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Set creation (setOf, mutableSetOf)
O(n)
Understanding Time Complexity

When we create sets in Kotlin, it's important to know how the time to build them grows as we add more items.

We want to understand how the work changes when the number of elements increases.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


val numbers = listOf(1, 2, 3, 4, 5)
val set1 = setOf(1, 2, 3, 4, 5)
val mutableSet = mutableSetOf()
for (num in numbers) {
    mutableSet.add(num)
}
    

This code creates a read-only set directly and a mutable set by adding elements one by one.

Identify Repeating Operations
  • Primary operation: Adding each element to the mutable set inside the loop.
  • How many times: Once for each element in the input list.
How Execution Grows With Input

As the number of elements increases, the number of add operations grows directly with it.

Input Size (n)Approx. Operations
10About 10 add operations
100About 100 add operations
1000About 1000 add operations

Pattern observation: The work grows in a straight line with the number of elements.

Final Time Complexity

Time Complexity: O(n)

This means the time to create the set grows directly in proportion to the number of items you add.

Common Mistake

[X] Wrong: "Adding elements to a set takes the same time no matter how many items there are."

[OK] Correct: Each element must be processed once, so more items mean more work, even if each add is fast.

Interview Connect

Understanding how set creation scales helps you explain efficiency when working with collections in real projects.

Self-Check

"What if we used a nested loop to add elements from two lists into a set? How would the time complexity change?"