0
0
Swiftprogramming~5 mins

Swift REPL and Playgrounds - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Swift REPL and Playgrounds
O(n)
Understanding Time Complexity

When using Swift REPL or Playgrounds, we often write small pieces of code to test ideas quickly.

We want to understand how the time it takes to run code grows as we try bigger inputs in these tools.

Scenario Under Consideration

Analyze the time complexity of the following Swift code snippet run in a Playground or REPL.


var sum = 0
for i in 1...n {
    sum += i
}
print(sum)

This code adds numbers from 1 to n and prints the total.

Identify Repeating Operations

Look for loops or repeated steps in the code.

  • Primary operation: The for-loop that adds each number to sum.
  • How many times: It runs once for each number from 1 to n.
How Execution Grows With Input

As n gets bigger, the loop runs more times, so the work grows with n.

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

Pattern observation: The number of steps grows directly with n.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the code grows in a straight line as the input size increases.

Common Mistake

[X] Wrong: "The loop runs a fixed number of times, so time is constant."

[OK] Correct: The loop depends on n, so if n grows, the loop runs more times, making the time grow too.

Interview Connect

Understanding how loops affect time helps you explain your code clearly and shows you can think about efficiency.

Self-Check

"What if we replaced the for-loop with a nested loop running from 1 to n inside the first loop? How would the time complexity change?"