Dictionary methods and default values in Swift - Time & Space Complexity
When using dictionary methods with default values, it's important to know how the time to run the code changes as the dictionary grows.
We want to find out how fast dictionary lookups and updates happen when using default values.
Analyze the time complexity of the following code snippet.
var counts = [String: Int]()
let words = ["apple", "banana", "apple", "orange", "banana", "apple"]
for word in words {
counts[word, default: 0] += 1
}
This code counts how many times each word appears in the list using a dictionary with default values.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the words array and updating dictionary entries.
- How many times: Once for each word in the list.
Each word causes one dictionary lookup and possibly an update. As the list grows, these operations happen more times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 lookups and updates |
| 100 | About 100 lookups and updates |
| 1000 | About 1000 lookups and updates |
Pattern observation: The number of operations grows directly with the number of words.
Time Complexity: O(n)
This means the time to count words grows in a straight line as the number of words increases.
[X] Wrong: "Using default values makes dictionary lookups slower because it adds extra work."
[OK] Correct: The default value is used only when the key is missing, and dictionary lookups are still very fast, so the overall speed stays proportional to the number of words.
Understanding how dictionary methods work with default values helps you write clear and efficient code, a skill valued in many programming tasks.
"What if we replaced the array with a nested loop over two arrays? How would the time complexity change?"
Practice
updateValue(_:forKey:) method do in a Swift dictionary?Solution
Step 1: Understand updateValue method purpose
TheupdateValue(_:forKey:)method changes the value for a specified key in the dictionary.Step 2: Check return behavior
This method returns the old value if the key existed, otherwise nil.Final Answer:
It updates the value for a given key and returns the old value if it existed. -> Option AQuick Check:
updateValue returns old value or nil [OK]
- Confusing updateValue with removeValue
- Thinking it returns the new value
- Assuming it creates a new dictionary
Solution
Step 1: Recall Swift dictionary default value syntax
Swift dictionaries allow accessing values with a default usingdict[key, default: defaultValue].Step 2: Compare options
let value = dict[key, default: 0] matches the correct syntax. let value = dict[key] ?? 0 uses nil-coalescing but is not the dictionary default syntax.Final Answer:
let value = dict[key, default: 0] -> Option AQuick Check:
Use dict[key, default:] for default values [OK]
- Using get() method which doesn't exist
- Confusing nil-coalescing with dictionary default syntax
- Using value(forKey:) which is for NSObject
var scores = ["Alice": 10, "Bob": 8] let oldValue = scores.updateValue(12, forKey: "Alice") let missingValue = scores.updateValue(5, forKey: "Charlie") print(oldValue, missingValue, scores)
Solution
Step 1: Understand updateValue return values
Updating "Alice" from 10 to 12 returns old value Optional(10). Adding "Charlie" returns nil because key was missing.Step 2: Check dictionary after updates
Dictionary now has "Alice":12, "Bob":8, and "Charlie":5.Final Answer:
Optional(10) nil ["Alice": 12, "Bob": 8, "Charlie": 5] -> Option CQuick Check:
updateValue returns old value or nil [OK]
- Expecting updateValue to return new value
- Forgetting Optional wrapping
- Not updating dictionary correctly
var dict = ["a": 1, "b": 2] let removed = dict.removeValue(forKey: "c") print(removed!)
Solution
Step 1: Understand removeValue return type
removeValue(forKey:) returns an Optional value. If key is missing, it returns nil.Step 2: Analyze force unwrapping
Force unwrappingremoved!when key "c" is missing causes a runtime crash.Final Answer:
Force unwrapping removed causes runtime crash if key missing. -> Option BQuick Check:
Force unwrap nil causes crash [OK]
- Assuming removeValue always returns a value
- Ignoring optional unwrapping
- Thinking removeValue removes all keys
var inventory = ["apple": 3, "banana": 5]. Write code to safely add 2 to the count of "orange", even if it doesn't exist yet, using dictionary default values. What is the correct way?Solution
Step 1: Understand safe addition with default
Usinginventory["orange", default: 0]returns 0 if "orange" key is missing.Step 2: Increment value safely
Adding 2 to this default value and assigning back toinventory["orange"]updates or creates the key safely.Final Answer:
inventory["orange"] = inventory["orange", default: 0] + 2 -> Option DQuick Check:
dict[key] = dict[key, default: 0] + value for safe increments [OK]
- Force unwrapping missing keys causing crash
- Using += on read-only default subscript
- Using updateValue without checking for nil
Ready to prove it?
Pass the test and this pattern moves unknown
