0
0
Swiftprogramming~5 mins

In-out parameters for mutation in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: In-out parameters for mutation
O(n)
Understanding Time Complexity

When using in-out parameters in Swift, we want to see how the time to run the code changes as the input size grows.

We ask: How does changing the input affect how long the function takes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func doubleValues(_ numbers: inout [Int]) {
    for i in 0 ..< numbers.count {
        numbers[i] *= 2
    }
}

var myNumbers = [1, 2, 3, 4, 5]
doubleValues(&myNumbers)
    

This function doubles each number in an array by changing the array directly using an in-out parameter.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A for-loop that goes through each element in the array.
  • How many times: Exactly once for each element in the array.
How Execution Grows With Input

As the array gets bigger, the function does more work because it doubles each number one by one.

Input Size (n)Approx. Operations
1010 times doubling
100100 times doubling
10001000 times doubling

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

Final Time Complexity

Time Complexity: O(n)

This means the time to run the function grows in a straight line with the size of the input array.

Common Mistake

[X] Wrong: "Using in-out parameters makes the function run faster because it changes data directly."

[OK] Correct: The speed depends on how many items you process, not just on using in-out. The loop still runs once per item.

Interview Connect

Understanding how in-out parameters affect time helps you explain how your code handles data changes efficiently in real projects.

Self-Check

"What if we changed the function to call itself recursively for each element? How would the time complexity change?"