0
0
Swiftprogramming~5 mins

Methods in structs in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Methods in structs
O(n)
Understanding Time Complexity

When we use methods inside structs, it's important to know how the time to run them changes as the data grows.

We want to find out how the method's work grows when the input changes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


struct NumberList {
    var numbers: [Int]

    func sum() -> Int {
        var total = 0
        for num in numbers {
            total += num
        }
        return total
    }
}
    

This code defines a struct with a method that adds up all numbers in an array.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that goes through each number in the array.
  • How many times: Once for each number in the array.
How Execution Grows With Input

As the list gets bigger, the method takes longer because it adds more numbers.

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

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 method takes longer in a straight line as the list gets bigger.

Common Mistake

[X] Wrong: "The method runs in the same time no matter how many numbers there are."

[OK] Correct: Because the method adds each number one by one, more numbers mean more work and more time.

Interview Connect

Understanding how methods inside structs work with data size helps you explain your code clearly and shows you know how performance changes with input.

Self-Check

"What if the method sorted the numbers before adding them? How would the time complexity change?"