Six interview problems that ask when two strings or items are the same kind. The move: compute one canonical key that all members share and no other group does.
You work on a build system, a chat app and a search engine. The six problems on this street come from all three. Each one asks when two items count as the same kind, and then groups, counts or finds them.
The meaning of "same kind" changes from problem to problem. Here is each rule and the key that would name its group.
| Problem | Two items are the same kind when | The key of a group |
|---|---|---|
| Isomorphic status codes | equal letters sit in equal places | the first-occurrence pattern |
| Chats filled by requested size | users asked for the same size | the size |
| Rotations of each other | one is the other, turned | the smallest rotation |
| Strings that differ by a shift | one is the other, moved along the alphabet | the differences from the first letter |
| Words made from a letter pool | every letter count fits in the pool | no single key |
| Anagram starts in a log | a window has the probe's letters | the letter counts of the window |
Read the last column. A good key is one value that all members of a group share. When there is none, as in the pool row, you compare counts instead of looking up a key.
The questions differ too. Some ask for the groups, some for how many groups there are, and some for the positions where a group appears.
Write the key before you write any code. The key is a canonical form: every member of a group turns into the same value, and members of different groups never do.
Two items get the same key exactly when they are the same kind. So one map from key to members, filled in one pass, holds every group.
A pattern key is the clearest case. Replace each letter by the number of the first place where it appeared. The word egg becomes 0-1-1, the word add becomes 0-1-1, and the word foo becomes 0-1-1 too. The word bar becomes 0-1-2.
Exercise · Predict the output: How many patterns?. The code turns each word into its first-occurrence pattern and puts the patterns in a set. What does it print?
words = ["egg", "add", "bar", "qux", "foo", "paper", "title"]
shapes = set()
for w in words:
seen = {}
parts = []
for ch in w:
if ch not in seen:
seen[ch] = len(seen)
parts.append(str(seen[ch]))
shapes.add("-".join(parts))
print(len(shapes))The key names a group, but it must also keep groups apart. A weaker key is a bug that no small test shows.
Take the sum of the letter codes as a key for anagrams. The words ad and bc both sum to 197, so they land in one group, and they are not anagrams.
A pattern key replaces each letter by the place where it first appeared, so egg, add and foo all read 0, 1, 1.
The Academy lesson Counting and grouping groups by a key, and Frequency, palindromes and anagrams counts letters. Keys, collisions and pitfalls says which values make safe keys. This street changes three things.
The key is the work. In the Academy the key was sorted letters or a count of 26 letters. Here every problem needs a different key, and one that is right for a rule can be wrong for the next.
Sorted letters join abc and acb, which are anagrams but not rotations. The smallest rotation of bca is abc, of cab is abc, and of acb is acb, so it joins the first two only.
Some keys wrap. A shift moves z round to a. The difference of a letter and the first letter must be taken modulo 26. Without it, az and ba look different, although moving every letter of az forward by one gives ba.
Exercise · Find the bug: Where does z go?. This counts the groups of keys that are shifts of one another. It is right unless a shift wraps round the end of the alphabet. Which line is wrong?
def count_shift_groups(keys):
groups = set()
for w in keys:
diffs = []
for ch in w:
diff = ord(ch) - ord(w[0])
diffs.append(str(diff))
groups.add(",".join(diffs))
return len(groups)A pool has no key, and a window has a moving one. A word fits a pool when each letter count is at most the pool's count. Equal counts would be wrong: the word ab fits the pool aabbc although the counts differ.
For anagram starts in a log, a window of the probe's length slides along. Rebuilding its counts at every start reads 99,001,000 letters for a 100,000-letter log and a 1,000-letter probe. Updating one letter in and one out reads about 200,000.
Sorted letters join anagrams, not only rotations. The smallest rotation keeps abc and acb apart.
Exercise · Break it: A map in one direction. This checks whether two status strings follow the same pattern. It maps each letter of the first string to the letter of the second string, and checks for a clash. Find an input where it is wrong.
def are_isomorphic(a, b):
mapping = {}
for x, y in zip(a, b):
if x in mapping and mapping[x] != y:
return False
mapping[x] = y
return TrueSolve them in this order. The first is a pattern key. The next two have a fixed group or no group, and the last three need a key built with care.
Before you code each problem, write two lines: what makes two items the same kind, and the key that names a group. If no single key fits, write the comparison you will make instead.
Give each problem about 20 minutes. Spend the first three on the two lines. Then test the key on two items that are almost the same kind, because a key that is too weak joins groups it should keep apart.
Three edge cases come back on most rungs. A word can be a single letter, two words can be identical, and a shift can wrap past z. Write one small test for each before you run anything.
When a solution fails, check the key first. Most wrong answers on this street come from a key that joins two groups, or from a rule that needs both directions and is checked in one.
Checkpoint · Grouping and anagrams
Q1/5 What must a canonical key do for a group of items?
Answer: B
A key that joins every member and separates every other group lets one map hold all groups. A key unique for every item would give no groups at all.
Q2/5 Which words fall in one group when the key is the first-occurrence pattern?
Answer: C
The words egg and foo both read 0-1-1. The word bar reads 0-1-2, add reads 0-1-1 but pairs with egg, and paper and pepper read differently.
Q3/5 Which key joins the words abc and acb into one group but is wrong when the groups are rotations?
Answer: B
The sorted letters of abc and acb are both abc, but acb is not a rotation of abc. The smallest rotation keeps them apart.
Q4/5 Why must the difference of each letter and the first letter be taken modulo 26 when grouping shifted words?
Answer: C
The words az and ba are a shift of one, but the differences are 25 and negative 1. They are equal modulo 26.
Q5/5 A word is spelled from a pool of letter tiles. When does the word fit?
Answer: C
The word ab fits the pool aabbc, although the counts are not equal. There is no group key, so compare counts letter by letter.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.