Try-catch as an expression in Kotlin - Time & Space Complexity
We want to understand how the time needed to run a try-catch expression changes as the input or operations inside it grow.
Specifically, we ask: how does using try-catch as an expression affect the program's running time?
Analyze the time complexity of the following code snippet.
fun parseNumber(input: String): Int = try {
input.toInt()
} catch (e: NumberFormatException) {
-1
}
fun processList(inputs: List): List {
return inputs.map { parseNumber(it) }
}
This code tries to convert each string in a list to an integer using try-catch as an expression.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The map function loops over each element in the input list.
- How many times: Once for each string in the list (n times if list size is n).
Each input string is processed once, so the total work grows directly with the number of inputs.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 conversions and try-catch checks |
| 100 | About 100 conversions and try-catch checks |
| 1000 | About 1000 conversions and try-catch checks |
Pattern observation: The work increases evenly as the list size grows.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of input strings.
[X] Wrong: "Try-catch blocks always make the code run slower by a lot."
[OK] Correct: The try-catch expression itself does not add repeated overhead; it only handles exceptions when they happen. Normal execution without exceptions runs almost as fast as code without try-catch.
Understanding how try-catch as an expression affects time helps you write clear and efficient Kotlin code, a skill valued in many coding challenges and real projects.
What if the parseNumber function threw exceptions for most inputs? How would that affect the time complexity?