0
0
Kotlinprogramming~5 mins

Collection size and emptiness checks in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Collection size and emptiness checks
O(1)
Understanding Time Complexity

When working with collections, checking if they are empty or finding their size is common.

We want to know how the time it takes to do these checks changes as the collection grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fun checkCollection(collection: Collection<Any>) {
    if (collection.isEmpty()) {
        println("Collection is empty")
    } else {
        println("Collection size is ${collection.size}")
    }
}
    

This code checks if a collection is empty and then prints its size if not empty.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking if the collection is empty and getting its size.
  • How many times: Each check happens once per function call.
How Execution Grows With Input

Checking emptiness or size usually takes the same time no matter how big the collection is.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The time stays about the same even if the collection grows larger.

Final Time Complexity

Time Complexity: O(1)

This means checking if a collection is empty or getting its size takes the same short time no matter how many items it holds.

Common Mistake

[X] Wrong: "Checking size or emptiness takes longer as the collection grows."

[OK] Correct: Most collections keep track of their size internally, so these checks do not need to count items each time.

Interview Connect

Understanding that size and emptiness checks are quick helps you write efficient code and explain your choices clearly in interviews.

Self-Check

"What if the collection was a linked list without a stored size? How would the time complexity change?"