0
0
Swiftprogramming~5 mins

Functions returning tuples in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Functions returning tuples
O(n)
Understanding Time Complexity

We want to understand how long it takes for a function that returns multiple values as a tuple to run.

Specifically, how does the time change when the input size changes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func minMax(numbers: [Int]) -> (min: Int, max: Int)? {
    guard !numbers.isEmpty else { return nil }
    var currentMin = numbers[0]
    var currentMax = numbers[0]
    for number in numbers {
        if number < currentMin { currentMin = number }
        if number > currentMax { currentMax = number }
    }
    return (currentMin, currentMax)
}
    

This function finds the smallest and largest numbers in an array and returns them as a tuple.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

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

As the array gets bigger, the function checks more numbers one by one.

Input Size (n)Approx. Operations
10About 10 checks
100About 100 checks
1000About 1000 checks

Pattern observation: The number of checks grows directly with the size of the input.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the input gets bigger.

Common Mistake

[X] Wrong: "Returning a tuple makes the function slower because it returns multiple values."

[OK] Correct: Returning a tuple just groups values together; it does not add extra loops or checks, so it does not slow down the function.

Interview Connect

Understanding how loops affect time helps you explain your code clearly and shows you can think about efficiency, which is a great skill for any coding challenge.

Self-Check

"What if the function also sorted the array before finding min and max? How would the time complexity change?"