Type checking with is operator in Kotlin - Time & Space Complexity
We want to understand how long it takes to check an object's type using the is operator in Kotlin.
How does the time needed change as we check more objects?
Analyze the time complexity of the following code snippet.
fun countStrings(items: List<Any>): Int {
var count = 0
for (item in items) {
if (item is String) {
count++
}
}
return count
}
This code counts how many items in a list are strings by checking each item's type.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list and checking its type with
is. - How many times: Once for every item in the list.
As the list gets bigger, the number of type checks grows directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 type checks |
| 100 | 100 type checks |
| 1000 | 1000 type checks |
Pattern observation: The work doubles when the list size doubles, growing in a straight line.
Time Complexity: O(n)
This means the time to check types grows directly with the number of items in the list.
[X] Wrong: "Type checking with is is instant and does not depend on list size."
[OK] Correct: Each item must be checked one by one, so more items mean more checks and more time.
Understanding how type checks scale helps you write efficient code and explain your reasoning clearly in interviews.
"What if we checked types only for the first half of the list? How would the time complexity change?"