Foundations
3 / 170FoundationsLesson 3 of 5About 37 min
The hash table is the highest-leverage tool in the whole course. This is how you drive it in Python.
Checking whether a value is in a list takes time proportional to the length of the list. Checking whether it is in a set or a dict takes constant time on average. Almost every time you turn an O(n squared) solution into an O(n) one, that swap is what did it.
values = [4, 8, 15, 16, 23, 42] print(23 in values) # O(n), scans until foundprint(23 in set(values)) # O(1) average, one hash lookupA set holds distinct values with no order. Use it whenever the question is membership rather than counting.
seen = set()seen.add(3)seen.add(3) # adding twice changes nothingprint(len(seen), 3 in seen) a = {1, 2, 3}b = {2, 3, 4}print(a & b, a | b, a - b) # intersection, union, differenceA dict maps keys to values. Since Python 3.7 it keeps insertion order, which is occasionally useful and should never be relied on for correctness in an interview answer unless you say so out loud.
ages = {"ana": 31, "bo": 27}ages["cy"] = 45 print(ages["ana"])print(ages.get("dee")) # None instead of KeyErrorprint(ages.get("dee", 0)) # supply your own default for name, age in ages.items(): print(name, age)Counting occurrences is so common that Python ships two tools for it. defaultdict makes a missing key spring into existence with a default; Counter goes further and counts an iterable in one call.
from collections import Counter, defaultdict counts = defaultdict(int)for ch in "banana": counts[ch] += 1 # no need to check whether ch exists yetprint(dict(counts)) print(Counter("banana"))print(Counter("banana").most_common(2)) groups = defaultdict(list)for word in ["ant", "bee", "ape"]: groups[word[0]].append(word)print(dict(groups))Comprehensions build a list, set, or dict in one expression. Used well they remove noise. Used badly they hide a nested loop inside something that looks like a single line, so keep them to one level in interview code.
nums = [1, 2, 3, 4, 5, 6] print([n * n for n in nums if n % 2 == 0])print({n % 3 for n in nums})print({n: n * n for n in nums if n < 4})Read carefully. Type the two lines of output.
from collections import defaultdict d = defaultdict(int)d["a"] = 1print(d["b"])print(len(d))Select every value that Python will accept as a dictionary key.
Three functions built on dicts and sets. first_repeat returns the first value that appears twice, scanning left to right, or None. char_counts returns a plain dict of character counts. common_elements returns the values present in both lists, sorted ascending.
Tests
print(first_repeat([1, 3, 5, 3, 1]))print(first_repeat([1, 2, 3]))print(char_counts("banana"))print(common_elements([4, 1, 2, 1], [2, 4, 9]))Output
Run tests to see output.