Collection size and emptiness checks in Kotlin - Time & Space 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.
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 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.
Checking emptiness or size usually takes the same time no matter how big the collection is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays about the same even if the collection grows larger.
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.
[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.
Understanding that size and emptiness checks are quick helps you write efficient code and explain your choices clearly in interviews.
"What if the collection was a linked list without a stored size? How would the time complexity change?"