In-out parameters for mutation in Swift - Time & Space 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?
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 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.
As the array gets bigger, the function does more work because it doubles each number one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times doubling |
| 100 | 100 times doubling |
| 1000 | 1000 times doubling |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to run the function grows in a straight line with the size of the input array.
[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.
Understanding how in-out parameters affect time helps you explain how your code handles data changes efficiently in real projects.
"What if we changed the function to call itself recursively for each element? How would the time complexity change?"