0
0
Kotlinprogramming~5 mins

Finally block behavior in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Finally block behavior
O(n)
Understanding Time Complexity

We want to understand how the time taken by a Kotlin program changes when it uses a finally block.

Specifically, we ask: does adding a finally block change how long the program runs as input grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

fun processList(items: List<Int>) {
    try {
        for (item in items) {
            println(item)
        }
    } finally {
        println("Done processing")
    }
}

This code prints each item in a list, then always prints "Done processing" at the end.

Identify Repeating Operations
  • Primary operation: The for loop that prints each item in the list.
  • How many times: Once for each item in the list (n times).
  • Finally block: Runs exactly once after the loop finishes.
How Execution Grows With Input

The loop runs once per item, so if the list has more items, the time grows proportionally.

Input Size (n)Approx. Operations
10About 10 prints + 1 finally print
100About 100 prints + 1 finally print
1000About 1000 prints + 1 finally print

Pattern observation: The time grows roughly in a straight line with the number of items. The finally block adds a fixed small cost.

Final Time Complexity

Time Complexity: O(n)

This means the time grows directly with the number of items; the finally block does not change this growth.

Common Mistake

[X] Wrong: "The finally block runs multiple times and makes the program slower as the list grows."

[OK] Correct: The finally block runs only once after the loop, so it adds a fixed cost, not one per item.

Interview Connect

Understanding how finally blocks behave helps you explain program flow clearly and reason about performance in real code.

Self-Check

What if the finally block contained a loop over the same list? How would the time complexity change?