Generic function declaration in Kotlin - Time & Space 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?
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 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.
As the list gets bigger, the function prints more items, so it does more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print actions |
| 100 | 100 print actions |
| 1000 | 1000 print actions |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items in the list.
[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.
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.
"What if we changed the function to print only the first half of the list? How would the time complexity change?"