0
0
Swiftprogramming~5 mins

Limitations and best practices in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Limitations and best practices
O(n)
Understanding Time Complexity

When we write code, it is important to know how fast it runs as the input grows.

This helps us avoid slow programs and choose better ways to solve problems.

Scenario Under Consideration

Analyze the time complexity of this example function.


func findFirstEven(numbers: [Int]) -> Int? {
    for number in numbers {
        if number % 2 == 0 {
            return number
        }
    }
    return nil
}

This function looks for the first even number in a list and stops when it finds one.

Identify Repeating Operations

Look at what repeats in the code.

  • Primary operation: Looping through the list of numbers.
  • How many times: Up to the length of the list, but may stop early.
How Execution Grows With Input

The time to run depends on where the first even number is.

Input Size (n)Approx. Operations
10Between 1 and 10 checks
100Between 1 and 100 checks
1000Between 1 and 1000 checks

Pattern observation: The work grows with input size but can stop early if the answer is found.

Final Time Complexity

Time Complexity: O(n)

This means the time grows roughly in proportion to the size of the input list in the worst case.

Common Mistake

[X] Wrong: "The function always checks every number in the list."

[OK] Correct: The function stops as soon as it finds an even number, so it may check fewer items.

Interview Connect

Understanding how loops and early exits affect time helps you explain your code clearly and choose better solutions.

Self-Check

"What if the function searched for all even numbers instead of stopping at the first? How would the time complexity change?"