0
0
Kotlinprogramming~5 mins

Any type as universal base in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Any type as universal base
O(n)
Understanding Time Complexity

When using Kotlin's Any type as a universal base, it's important to see how operations on these objects grow with input size.

We want to know how the program's work changes as we handle more Any objects.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fun printAll(items: List) {
    for (item in items) {
        println(item.toString())
    }
}

This code prints the string form of each item in a list of Any objects.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each item in the list.
  • How many times: Once for every item in the list.
How Execution Grows With Input

As the list gets bigger, the program prints more items, so the work grows steadily.

Input Size (n)Approx. Operations
1010 print calls
100100 print calls
10001000 print calls

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the list gets bigger.

Common Mistake

[X] Wrong: "Using Any makes the code slower because it has to check types for every item."

[OK] Correct: The loop runs once per item regardless of type. The toString() call is a simple method call and does not add extra loops or checks that change the overall time growth.

Interview Connect

Understanding how operations on universal types like Any scale helps you explain performance clearly and confidently in interviews.

Self-Check

"What if we changed the list to a nested list of Any objects? How would the time complexity change?"