iq.lab
Python starts when a code cell comes near or you run one
03 Arrays and hash maps

Lesson 4 of 5

Grouping by a key

One walk with a dict from key to list puts every item in its group, and choosing the key is the whole problem. Then two more O(n) jobs: counts used as list positions to find the most frequent values, and a set that finds where each run of consecutive numbers starts.

About 1 hour 50 minutes, with the 3 problems worked in it
By the end you can
  • Group items in one walk with a dict of lists, with and without defaultdict(list)

  • Choose a key that is equal for two items exactly when they belong together, and spot keys that split or merge groups

  • Find the k most frequent values with buckets indexed by count, in O(n) time

  • Find the longest run of consecutive numbers with a set and the start-of-a-run check, in O(n) time

  • Explain why a while loop inside a for loop can still cost O(n) in total

At work you group rows without thinking about it. GROUP BY customer_id puts each customer's orders together. GROUP BY LOWER(email) puts Ana@x.com and ana@x.com together. The expression after GROUP BY decides which rows count as the same.

Python has no GROUP BY clause, so you build one: a walk over the items, and a dict that maps each key to the list of items with that key. The previous lesson's notebooks kept a count, a seen mark or a position for each item; this one keeps the items themselves. The code is short and hardly changes from problem to problem. What changes is the key. In grouping problems, choosing the key is the whole problem.

We build the dict of lists first, then choose keys for anagrams. Then we use hash maps for two more classic mediums: the most frequent values, and the longest run of consecutive numbers.

A dict of lists

How do you put items into groups in one walk? Start with a key you can compute in your head: the length of a word. We want ["ox", "cat", "be", "dog"] to come out as two groups: the 2-letter words ox and be, and the 3-letter words cat and dog.

A quick reminder about dicts. A dict maps keys to values. groups[key] reads the value stored under key, and reading a key that is not there raises a KeyError. key in groups asks whether the key is there. So each word takes three moves: compute its key; if the key is new, store an empty list under it; append the word to the list under its key.

The trace runs that on our four words. Before you step through, guess what groups holds at the end, and which key comes first.

Step throughGrouping words by length
Step 1 of 24
Line 1 is about to run.
def group_by_length(words):
groups = {}
for word in words:
key = len(word)
if key not in groups:
groups[key] = []
groups[key].append(word)
return groups
Names
no names yet
Output
(nothing printed yet)

Line 7 never assigns to groups. groups[key] hands back the list stored under the key, and .append adds to that same list, so the dict sees the new word. The change line groups[2]: [] → ["ox"] shows exactly that: the list under key 2 grew.

A dict keeps its keys in the order they were first added, so groups come out in the order their first items appeared: 2 before 3, because "ox" came before "cat". Inside a group, the words keep the order of the walk.

The promise is what makes the result right: after each word, every word visited sits in exactly one list, the list under its own key. When the walk ends, every word has been visited, so every word is in its group.

Try a new key before going on. n % 3 is the remainder when n is divided by 3: 7 % 3 is 1.

PredictGrouping by remainder

Read the loop and type exactly what it prints, in Python's own format.

groups = {}
for n in [4, 9, 7, 5, 6]:
    key = n % 3
    if key not in groups:
        groups[key] = []
    groups[key].append(n)
print(groups)

Now build one yourself. The key this time is the last letter of each word.

Put in orderGroup by last letter

Put the lines in order to build group_by_last_letter(words), which returns a dict from each last letter to the list of words that end with it, in the order the words appear. Indentation is part of each line. Two of the lines do not belong.

word[-1] is the last character of word: a negative index counts from the end.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • groups[key] = []
    • groups = {}
    • key = word[-1]
    • groups[key] = word
    • groups[key].append(word)
    • return groups
    • groups[key] = []
    • def group_by_last_letter(words):
    • for word in words:
    • if key not in groups:

    The two lines that start an empty group appear in every grouping loop, so Python has a shortcut, and the hash map lesson already used it. A reminder: defaultdict(list) is a dict that stores a new empty list the first time you read a key that is missing. It comes from the collections module, and list is what it calls to make each new value (list() returns []). With it, the loop body is one line:

    from collections import defaultdict
    
    def group_by_length(words):
        groups = defaultdict(list)
        for word in words:
            groups[len(word)].append(word)
        return groups

    Choosing the key

    What key puts anagrams together? A reminder from the last lesson: two words are anagrams when one is a rearrangement of the other, with the same letters, each used the same number of times. "pat", "tap" and "apt" are anagrams of each other, and so are "ten" and "net".

    A key works when it has one property: two items get equal keys exactly when they belong in the same group. Both directions matter. If two anagrams can get different keys, their group splits in two. If two words that are not anagrams can get the same key, two groups merge into one.

    Sorting the letters gives every anagram the same string. sorted("pat") returns ["a", "p", "t"], the letters as a list in alphabetical order. "tap" and "apt" have the same letters, so they sort to the same list. Then "".join(...) glues the letters back into one string: "apt".

    Why glue them back? A dict key must be hashable: a value that cannot change, so its hash stays the same while it is stored. As the hash map lesson showed, the dict files each key in a bucket chosen from the key's hash, and a key that changed later would sit in the wrong bucket. Strings, numbers and tuples of them cannot change, so they can be keys. Lists can change, so groups[sorted(word)] raises TypeError: cannot use 'list' as a dict key (unhashable type: 'list').

    Here is the anagram grouping on five words. Guess first: how many groups come out, and which words share one?

    Step throughGrouping anagrams by sorted letters
    Step 1 of 22
    Line 1 is about to run.
    from collections import defaultdict
    def group_anagrams(words):
    groups = defaultdict(list)
    for word in words:
    key = "".join(sorted(word))
    groups[key].append(word)
    return list(groups.values())
    Names
    no names yet
    Output
    (nothing printed yet)

    The cost is the grouping walk plus the key. The walk makes one dict lookup per word, and sorting a word of k letters costs O(k log k), so n words of up to k letters cost O(n · k log k) time.

    Not every key that looks reasonable keeps the property. Check each one against small words.

    Quick checkWhich keys group anagrams?

    Each option is a key computed for every word. Which keys put two lowercase words in the same group exactly when they are anagrams, and can be used as a dict key? Pick every one that works.

    Choose every option that applies, then check.

    A second key avoids sorting: count the letters, the same counts the last lesson compared to check two anagrams. Make a list of 26 zeros, one per letter, and add 1 at the letter's position for each letter of the word. ord(c) is a character's code number (ord("a") is 97), so ord(c) - ord("a") is the letter's position in the alphabet: 0 for a, 1 for b, 25 for z. Turn the list into a tuple so it can be a key. Run it, and try your own words:

    ⌘+Enter runs · edit freelyPython starts when a code cell comes near or you run one

    The first two lines print (1, 2, 0) and (1, 1, 0), so "abb" and "ab" stay apart, and the last prints True: the anagrams "tap" and "pat" share a key. Counting costs O(k) for a word of k letters (plus a fixed 26 to build the tuple), against O(k log k) for sorting. For short words both are fast; in an interview, pick one and say why.

    The key decides what "the same" means. Change the question and the key changes with it, while the loop stays put:

    Code itSame letters, any counts

    Write group_by_letters(words) for a list of lowercase words. Two words share a group when they use the same letters, however many times each one appears: "loop", "pool", "lop" and "polo" all use l, o and p. Return the groups as a list of lists, in any order. Then press Watch it run to see the dict fill.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

    The full problem is next. Name the brute force first, as you would in the room. Without a dict, you keep a list of groups and compare each new word with the first word of every group so far. With g groups, one word costs up to g comparisons, so when most words stand alone the total grows like n2. The dict replaces that scan with one lookup. Write it from a blank editor before you look back at the trace.

    mediumHash maps and sets target 25 min

    Group anagrams

    You get a list of lowercase words. Two words are anagrams when one is a rearrangement of the other: the same letters, each used the same number of times. Put the words into groups so that two words share a group exactly when they are anagrams, and return the groups as a list of lists.

    Every word lands in exactly one group. A word with no anagram forms a group of one, and a word that appears twice appears twice in its group. A word can be empty, and all empty words are anagrams of each other. The groups can come in any order, and so can the words inside each group.

    Example 1
    Inputwords = ["rat", "tops", "art", "elf", "stop", "tar"]Output[["rat", "art", "tar"], ["tops", "stop"], ["elf"]]

    rat, art and tar each use one a, one r and one t. elf has no anagram, so it is a group of one.

    Example 2
    Inputwords = ["ab", "abb", "bba"]Output[["ab"], ["abb", "bba"]]

    abb and bba both have one a and two b's. ab has the same letters but different counts, so it stays apart.

    Example 3
    Inputwords = ["no", "on", "no"]Output[["no", "on", "no"]]

    Both copies of no belong to the group.

    Constraints
    • 1 ≤ len(words) ≤ 104

    • 0 ≤ len(word) ≤ 100 for each word

    • Words hold only lowercase English letters, a to z.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    The loop never changed; only the key did. A key must be equal exactly when two items belong together, and it must be hashable. The speed test has 9,000 words in 4,500 groups: the scan over the groups costs about 20 million comparisons there, while the dict makes one lookup per word. All empty words share the key "", so they form one group. Valid sudoku, on the Practice page, uses the same move with a tuple key: (r // 3, c // 3) names each 3 by 3 box.

    Counts as list positions

    Which k values appear most often in a list? Take nums = [5, 3, 5, 1, 3, 5] and k = 2. The answer is 5 and 3.

    Step 1 is the counting pattern. Counter(nums) (from collections) is a dict from each value to how many times it appears, built in one pass. Here it holds 5 three times, 3 twice and 1 once.

    Step 2 picks the biggest counts. Sorting the distinct values by count and taking the first k is a fine first answer, at O(d log d) for d distinct values. It is the query SELECT value FROM t GROUP BY value ORDER BY COUNT(*) DESC LIMIT 2. In Python, sorted(counts, ...) walks the dict's keys, and key=counts.get (passed without parentheses, like key=len) sorts each value by its count:

    ⌘+Enter runs · edit freelyPython starts when a code cell comes near or you run one

    It prints the counts, then [5, 3]. Can we skip the sort?

    A count is a whole number between 1 and n, where n is len(nums): no value appears more than n times. So a count can be a list position. Make buckets, a list of n + 1 empty lists, and put each value into buckets[count]. Then read the buckets from the top end: the values come out from most frequent to least, without a single comparison between counts. This is bucket sort by frequency: the position does the sorting.

    Four pieces of Python in the trace need a word first:

    • [[] for _ in range(len(nums) + 1)] makes a fresh empty list for each position from 0 to n. The name _ means "a loop variable we never read". ([[]] * (n + 1) would put one shared list in every position, the shared-row trap [[0] * 3] * 2 from the first lesson of this module.)
    • The list has n + 1 positions, 0 to n, so that buckets[n] exists for the case where every item is the same value.
    • counts.items() hands out each key with its value, as pairs: (5, 3), then (3, 2), then (1, 1). for value, count in counts.items(): unpacks each pair into two names, the way low, high = (3, 8) does.
    • range(a, b, -1) counts down from a and stops before b: range(6, 0, -1) gives 6, 5, 4, 3, 2, 1.

    The arrow under buckets shows count. Before you step through, guess which buckets end up holding a value, and at which count the second walk returns.

    Step throughTop k from buckets of counts
    Step 1 of 37
    Line 1 is about to run.
    from collections import Counter
    def top_k_frequent(nums, k):
    counts = Counter(nums)
    buckets = [[] for _ in range(len(nums) + 1)]
    for value, count in counts.items():
    buckets[count].append(value)
    result = []
    for count in range(len(nums), 0, -1):
    for value in buckets[count]:
    result.append(value)
    if len(result) == k:
    return result
    return result
    Names
    no names yet
    Output
    (nothing printed yet)

    Now run the same function in your head on a new list.

    Work it outHow far down the buckets?

    Run the trace's top_k_frequent in your head on nums = [2, 7, 2, 2, 7, 1, 2] with k = 2. The second loop tries count = 7 first, then 6, and so on down. How many values of count does it try, including the one where it returns?

    values of count tried

    Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

    The promise is why the first k values are the answer. Values enter result from the most frequent down, because every value with a bigger count sits in a higher bucket, and higher buckets are opened first.

    mediumHash maps and setsSorting target 25 min

    Top k frequent elements

    You get a list of integers nums and a whole number k. Return a list of the k values that appear most often in nums, each value once.

    The input always has a clean cut: each of those k values appears more often than every value left out, so exactly one answer exists. Return its k values in any order.

    Example 1
    Inputnums = [4, 4, 1, 4, 2, 2, 3], k = 2Output[4, 2]

    4 appears three times and 2 twice. 1 and 3 appear once each.

    Example 2
    Inputnums = [7], k = 1Output[7]

    7 is the only value, so it is the most frequent.

    Example 3
    Inputnums = [5, -1, 5, -1, 8], k = 2Output[5, -1]

    5 and -1 appear twice each, 8 once. [-1, 5] is also correct.

    Constraints
    • 1 ≤ len(nums) ≤ 105

    • -104 ≤ nums[i] ≤ 104

    • 1 ≤ k ≤ the number of distinct values in nums

    • The answer is unique: there is no tie at the cut.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    The bucket list has n + 1 slots, however few distinct values there are. Here that stays within O(n), the same as counting. With a billion items and a few thousand distinct values it would be a billion mostly empty buckets: sort the few thousand counts instead, or keep a heap of size k (module 9). The problem also promises no tie at the cut, so the k-th value taken never leaves behind another value with the same count. Ties and huge inputs are both among the problem's follow-ups.

    A set and the start of a run

    What is the longest run of consecutive integers in a list that is not sorted? A consecutive run is a stretch of integers with no gaps, such as 1, 2, 3, 4. In [7, 1, 3, 2, 8, 4] the numbers 1, 2, 3 and 4 are all present, scattered around the list: a run of 4. 7 and 8 make a run of 2. A run here always means a whole run, one that cannot grow at either end. 2, 3, 4 has no gaps either, but it sits inside the run 1 to 4, which cannot grow because 0 and 5 are missing.

    Sorting works but costs O(n log n): after sorting, each run sits in one stretch, and one scan that skips repeated values finds the longest. The problem asks for O(n), so we need to find runs without putting the numbers in order.

    The notebook is a set. A reminder: x in a_set takes O(1) time on average, about the same however many values the set holds, while x in a_list checks the items one by one, O(n). Put every number in a set called present. From any number x, measure the run upward: is x + 1 present? x + 2? Stop at the first missing number.

    Measuring from every number repeats work. On 1, 2, 3, 4 we measure from 1 (looking up 2, 3, 4 and the missing 5: four lookups), then again from 2 (three), from 3 (two) and from 4 (one). For one run of n numbers that is n(n + 1)/2 lookups: O(n2).

    Only the start of a run needs to measure it. A number x starts a run exactly when x - 1 is missing. 2 sees 1 in the set, so 2 is inside a run that 1 measures, and 2 skips. The loop skips with continue, which ends the current pass and moves to the next value.

    Before you step through, guess which numbers of [7, 1, 3, 2, 8, 4] start a run.

    Step throughMeasuring each run from its start
    Step 1 of 37
    Line 1 is about to run.
    def longest_consecutive(nums):
    present = set(nums)
    best = 0
    for x in present:
    if x - 1 in present:
    continue
    length = 1
    while x + length in present:
    length += 1
    best = max(best, length)
    return best
    Names
    no names yet
    Output
    (nothing printed yet)

    Count the lookups yourself on one long run, both ways. This is where the trick pays.

    On paperLookups on one long run

    Take nums = [4, 6, 1, 5, 3, 2]: one run, 1 to 6. On paper, count every in lookup two ways. First the brute force, which measures upward from every value. Then the trace's version, which checks x - 1 in present for every value and measures only from starts. How many lookups does the start version make in total?

    Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.

    lookups in the start version

    Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

    Every run has exactly one start, its smallest number, and that number is in the set, so the walk reaches it. From there the while loop measures the whole run, because it stops only at the first missing number. When the walk ends, every run has been measured once.

    mediumHash maps and sets target 25 min

    Longest consecutive sequence

    You get a list of integers nums in no particular order. A consecutive run is a stretch of integers with no gaps, such as 4, 5, 6, 7. Return the length of the longest run whose numbers all appear somewhere in nums.

    The numbers of a run do not need to sit next to each other in the list, and a value that appears more than once counts once. An empty list gives 0. Aim for O(n) time, faster than sorting.

    Example 1
    Inputnums = [8, 3, 50, 5, 4, 9]Output3

    3, 4 and 5 are all present. 8 and 9 form a run of 2, and 50 a run of 1.

    Example 2
    Inputnums = [2, 1, 2, 0, -1]Output4

    The run is -1, 0, 1, 2. The second 2 adds nothing.

    Example 3
    Inputnums = []Output0

    No numbers, so no run.

    Constraints
    • 0 ≤ len(nums) ≤ 105

    • -109 ≤ nums[i] ≤ 109

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    Loop over present, not nums. A start that appears many times in nums would be measured once per copy; one of the speed tests puts 10,000 extra copies of 0 in front of the run 0 to 9,999. The set holds each value once, so each run is measured once. And best starts at 0, not 1, so an empty list never enters the loop and returns 0.

    Last, the complexity probe. The words you write here are the words you will say in the room.

    Say itA loop inside a loop, and still O(n)

    You finish longest consecutive sequence, and the interviewer points at your code: "There is a while loop inside a for loop. Isn't that O(n2)?" Write what you would say.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Prefix sums