0
0
Swiftprogramming~5 mins

Var for variables (mutable) in Swift - Time & Space Complexity

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

Let's see how using var for variables affects the time it takes for a program to run.

We want to know how the program's steps grow when we change or update variables.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


var total = 0
let numbers = [1, 2, 3, 4, 5]
for number in numbers {
    total += number
}
print(total)
    

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

Identify Repeating Operations

Look for loops or repeated steps.

  • Primary operation: Adding each number to total inside the loop.
  • How many times: Once for each number in the array.
How Execution Grows With Input

As the list of numbers gets bigger, the program adds more numbers one by one.

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

Pattern observation: The number of steps 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 as the input size grows.

Common Mistake

[X] Wrong: "Using var makes the code slower because variables change all the time."

[OK] Correct: Changing a variable itself is quick; the main time cost comes from how many times you do it, not that it changes.

Interview Connect

Understanding how loops and variable changes affect time helps you explain your code clearly and think about efficiency in real projects.

Self-Check

"What if we replaced the for loop with a function that sums the array recursively? How would the time complexity change?"