Why collection algorithms matter in Swift - Performance Analysis
When working with collections like arrays or lists, the way we search, sort, or filter them affects how fast our program runs.
We want to know how the time needed changes as the collection gets bigger.
Analyze the time complexity of the following code snippet.
let numbers = [1, 3, 5, 7, 9]
func containsNumber(_ target: Int, in array: [Int]) -> Bool {
for number in array {
if number == target {
return true
}
}
return false
}
let result = containsNumber(5, in: numbers)
This code checks if a number exists in an array by looking at each item one by one.
- Primary operation: Looping through the array elements one by one.
- How many times: Up to once for each item until the target is found or the end is reached.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows directly with the size of the array.
Time Complexity: O(n)
This means the time to find a number grows in a straight line as the list gets bigger.
[X] Wrong: "Searching an unsorted list is always fast because computers are quick."
[OK] Correct: Even fast computers need to check each item one by one if the list is unsorted, so bigger lists take more time.
Understanding how collection algorithms grow with input size helps you explain your choices clearly and shows you know how to write efficient code.
"What if the array was sorted and we used a method that splits the search area in half each time? How would the time complexity change?"
Practice
Solution
Step 1: Understand the purpose of collection algorithms
Collection algorithms are designed to help manage data by finding, sorting, filtering, and checking items quickly.Step 2: Evaluate the options based on this purpose
They help find, sort, and filter data easily and efficiently. correctly states their role in making data handling easier and efficient. Other options describe incorrect or negative effects.Final Answer:
They help find, sort, and filter data easily and efficiently. -> Option AQuick Check:
Collection algorithms improve data handling = B [OK]
- Thinking algorithms slow down the app
- Believing algorithms only work with numbers
- Assuming algorithms make code complex
filter algorithm on an array numbers to get only even numbers in Swift?Solution
Step 1: Understand the filter syntax in Swift
The filter method takes a closure that returns true for elements to keep. The condition for even numbers is number % 2 == 0.Step 2: Check each option for correct syntax and logic
let evens = numbers.filter { $0 % 2 == 0 } uses the correct modulo operator and comparison. let evens = numbers.filter { $0 / 2 == 0 } uses division incorrectly. let evens = numbers.filter { $0 % 2 = 0 } uses assignment (=) instead of comparison (==). let evens = numbers.filter { $0 == 2 } filters only numbers equal to 2, not all evens.Final Answer:
let evens = numbers.filter { $0 % 2 == 0 } -> Option BQuick Check:
Correct filter syntax for evens = A [OK]
- Using / instead of % for even check
- Using = instead of == in condition
- Filtering only one number instead of all evens
let names = ["Anna", "Bob", "Cathy", "David"]
let result = names.contains { $0.hasPrefix("C") }
print(result)Solution
Step 1: Understand the contains method with a closure
The contains method checks if any element satisfies the condition. Here, it checks if any name starts with "C".Step 2: Check the array elements for the condition
"Cathy" starts with "C", so the condition is true, making result true.Final Answer:
true -> Option DQuick Check:
names contains prefix "C" = true [OK]
- Thinking contains checks all elements and returns false if any fail
- Confusing hasPrefix with contains
- Expecting syntax error due to closure
let numbers = [3, 1, 4, 2]
let sorted = numbers.sorted(by: { a, b in a > b })
print(sorted)Solution
Step 1: Understand the sorted(by:) closure logic
The closure defines the sorting order. Using 'a > b' sorts descending, not ascending.Step 2: Identify the intended sort order
Since the question implies sorting ascending, the closure should use 'a < b'. Other options are incorrect because sorted can take closures, arrays can be immutable for sorted, and parameter names are flexible.Final Answer:
The closure should use '<' instead of '>' to sort ascending. -> Option AQuick Check:
Use '<' for ascending sort closure [OK]
- Thinking sorted needs mutable array
- Believing closure parameter names are fixed
- Assuming sorted can't take closures
let scores = [10, 0, 5, 0, 8]. You want to create a dictionary where keys are the scores and values are the count of how many times each score appears, but you want to ignore zero scores. Which Swift code correctly uses collection algorithms to do this?Solution
Step 1: Filter out zero scores
The code filters scores to exclude zeros usingfilter { $0 != 0 }.Step 2: Group remaining scores and count occurrences
UsingDictionary(grouping:by:)groups scores by value, thenmapValues { $0.count }counts how many times each score appears.Final Answer:
let counts = Dictionary(grouping: scores.filter { $0 != 0 }, by: { $0 }).mapValues { $0.count } -> Option CQuick Check:
Filter zeros, group by score, count occurrences = D [OK]
- Using uniqueKeysWithValues which overwrites duplicates
- Not filtering zeros before counting
- Using reduce incorrectly without counting
Ready to prove it?
Pass the test and this pattern moves unknown
