0
0
Kotlinprogramming~5 mins

Generic function declaration in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Generic function declaration
O(n)
Understanding Time Complexity

When we write a generic function, it can work with many types of data. We want to see how the time it takes to run changes as the input size grows.

How does the function's work grow when we give it more items to handle?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fun <T> printAll(items: List<T>) {
    for (item in items) {
        println(item)
    }
}
    

This function takes a list of any type and prints each item one by one.

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 function prints more items, so it does more work.

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

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

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items in the list.

Common Mistake

[X] Wrong: "Because the function is generic, it must be slower or more complex."

[OK] Correct: The generic part only means it works with any type, but the loop still runs once per item, so the time depends on the list size, not the type.

Interview Connect

Understanding how generic functions behave helps you explain your code clearly and shows you know how performance depends on input size, a key skill in programming.

Self-Check

"What if we changed the function to print only the first half of the list? How would the time complexity change?"