Lesson 1 · Unit 04
Instant lookup
Sets and maps answer in one step
What you practise
- Set membership O(1) vs list scan O(n)
- Map get/set
- What a missing key does in each language
Try a question from this lesson
Pick one
Checking whether a name is on an unsorted list of 10,000 names means scanning it. Which idea would let you check in one step?
Correct answer
Give every name its own slot that you can jump to
Why
A hash set computes a slot number from the name itself and jumps straight there, like array indexing with names instead of numbers. Scanning from both ends is still a scan.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Sets: instant membership
A set answers "is x in here?" in O(1) on average, whatever its size. A list answers the same question by scanning: O(n).
The price: a set uses extra memory, keeps each value once, and has no positions.
guests = {"ada", "bo"}
print("bo" in guests) # True
print("cy" in guests) # False
guests.add("cy")
print(len(guests)) # 3const guests = new Set(["ada", "bo"]);
console.log(guests.has("bo")); // true
console.log(guests.has("cy")); // false
guests.add("cy");
console.log(guests.size); // 3const guests = new Set(["ada", "bo"]);
console.log(guests.has("bo")); // true
console.log(guests.has("cy")); // false
guests.add("cy");
console.log(guests.size); // 3Python note{} is an empty dict, not an empty set. Write set() for an empty set.
JavaScript noteA Set has .size, not .length, and .has(x) instead of the array method .includes(x).
TypeScript noteThis is inferred as Set<string> from the array. An empty one needs the type spelled out: new Set<string>().
Concept
Maps: a value for every key
A hash map stores key → value pairs. Storing a pair and looking a value up by its key are both O(1) on average.
It is called a dict in Python and a Map in JavaScript.
ages = {"ada": 36}
ages["cy"] = 41 # store
print(ages["ada"]) # 36
print("di" in ages) # False
print(len(ages)) # 2const ages = new Map([["ada", 36]]);
ages.set("cy", 41); // store
console.log(ages.get("ada")); // 36
console.log(ages.has("di")); // false
console.log(ages.size); // 2const ages = new Map([["ada", 36]]);
ages.set("cy", 41); // store
console.log(ages.get("ada")); // 36
console.log(ages.has("di")); // false
console.log(ages.size); // 2Python note"di" in ages checks the keys, not the values.
JavaScript noteA plain object {} also maps strings to values, but a Map accepts any key type, has .size, and has no inherited keys such as toString.
TypeScript noteThis is inferred as Map<string, number>. For an empty map write new Map<string, number>().
9 more exercises in the app
- 2× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.