0
0
Swiftprogramming~5 mins

Print function for output in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Print function for output
O(n)
Understanding Time Complexity

Let's see how the time it takes to print something grows as we print more items.

We want to know how the print function's work changes when printing many values.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


for number in 1...n {
    print(number)
}
    

This code prints numbers from 1 up to n, one by one.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The print statement inside the loop.
  • How many times: Exactly n times, once for each number from 1 to n.
How Execution Grows With Input

As n grows, the number of print actions grows the same way.

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

Pattern observation: The work grows directly with the number of items to print.

Final Time Complexity

Time Complexity: O(n)

This means the time to print grows in a straight line as you print more numbers.

Common Mistake

[X] Wrong: "Printing is instant and does not depend on how many items we print."

[OK] Correct: Each print takes some time, so printing more items takes more total time.

Interview Connect

Understanding how simple loops like printing scale helps you explain how programs handle bigger tasks step by step.

Self-Check

"What if we printed only every other number instead of all numbers? How would the time complexity change?"