Null safety in collections in Kotlin - Time & Space Complexity
When working with collections in Kotlin, null safety helps avoid errors by controlling which elements can be null.
We want to see how checking for nulls in collections affects the time it takes to run the code.
Analyze the time complexity of the following code snippet.
fun countNonNull(items: List): Int {
var count = 0
for (item in items) {
if (item != null) {
count++
}
}
return count
}
This code counts how many non-null strings are in a list that may contain null values.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the list once.
- How many times: Exactly once for every item in the list.
As the list gets bigger, the code checks each item one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of operations grows directly with the size of the list.
Time Complexity: O(n)
This means the time to count non-null items grows in a straight line as the list gets bigger.
[X] Wrong: "Checking for nulls inside the loop makes the code slower by a lot."
[OK] Correct: The null check is very quick and happens once per item, so it doesn't change the overall growth pattern.
Understanding how null safety checks affect performance shows you can write safe and efficient Kotlin code, a skill valued in many coding tasks.
"What if we used a nested list of nullable strings instead of a single list? How would the time complexity change?"