Elvis operator deep usage in Kotlin - Time & Space Complexity
We want to understand how using the Elvis operator affects the speed of code when it runs many times.
Specifically, how does the time to finish change as the input grows?
Analyze the time complexity of the following code snippet.
fun processList(items: List): List {
return items.map { it ?: "default" }
}
This code replaces null values in a list with "default" using the Elvis operator.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The map function loops over each item in the list once.
- How many times: Exactly once for each item in the input list.
As the list gets bigger, the code checks each item once, so the work grows steadily with the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of operations grows directly with the input size.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the list gets bigger.
[X] Wrong: "Using the Elvis operator makes the code slower because it adds extra checks inside the loop."
[OK] Correct: The Elvis operator is just a simple check done once per item, so it does not add extra loops or nested work. The overall time still grows linearly.
Understanding how simple operators like Elvis affect performance helps you explain your code choices clearly and confidently in interviews.
"What if we replaced the map with a nested loop that also uses the Elvis operator inside? How would the time complexity change?"