0
0
Kotlinprogramming~5 mins

Type checking with is operator in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Type checking with is operator
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the list gets bigger, the number of type checks grows directly with the number of items.

Input Size (n)Approx. Operations
1010 type checks
100100 type checks
10001000 type checks

Pattern observation: The work doubles when the list size doubles, growing in a straight line.

Final Time Complexity

Time Complexity: O(n)

This means the time to check types grows directly with the number of items in the list.

Common Mistake

[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.

Interview Connect

Understanding how type checks scale helps you write efficient code and explain your reasoning clearly in interviews.

Self-Check

"What if we checked types only for the first half of the list? How would the time complexity change?"