0
0
Kotlinprogramming~5 mins

Var for mutable references in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Var for mutable references
O(n)
Understanding Time Complexity

Let's see how using var for mutable references affects how long a program takes to run.

We want to know how the program's steps grow when we change the input size.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fun sumList(numbers: List): Int {
    var total = 0
    for (num in numbers) {
        total += num
    }
    return total
}

This code adds up all numbers in a list using a mutable variable total.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for loop that goes through each number in the list.
  • How many times: Once for every item in the list.
How Execution Grows With Input

As the list gets bigger, the program does more additions, one for each number.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

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

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the list size.

Common Mistake

[X] Wrong: "Using var makes the code slower because it changes values."

[OK] Correct: Changing a variable's value itself doesn't add extra loops or steps. The main time cost is from how many times the loop runs, not from using var.

Interview Connect

Understanding how mutable variables work helps you explain how your code runs step-by-step, which is a useful skill in interviews and real projects.

Self-Check

What if we replaced the for loop with a recursive function? How would the time complexity change?