What is Swift - Complexity Analysis
Time complexity helps us understand how the work a program does changes as the input grows.
For Swift, we want to see how fast or slow code runs when we give it more data.
Analyze the time complexity of the following code snippet.
func greet(names: [String]) {
for name in names {
print("Hello, \(name)!")
}
}
let friends = ["Anna", "Ben", "Cara"]
greet(names: friends)
This code says hello to each name in a list by printing a greeting.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each name in the array.
- How many times: Once for every name in the list.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 greetings printed |
| 100 | 100 greetings printed |
| 1000 | 1000 greetings printed |
Pattern observation: The work grows directly with the number of names. More names mean more greetings.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of names.
[X] Wrong: "The loop runs a fixed number of times no matter the list size."
[OK] Correct: The loop runs once for each name, so if the list grows, the loop runs more times.
Understanding how loops grow with input size is a key skill. It shows you can think about how code behaves with more data.
"What if we changed the loop to print greetings only for the first 5 names? How would the time complexity change?"