Knitting Pattern Shorthand
A knitting club writes patterns as lists of stitches: k for knit, p for purl, yo for yarn over. To shorten them, they find the most common pair of neighbouring stitches, give it one new symbol (k then p becomes kp), rewrite the pattern, and repeat.
This is byte pair encoding, how many language models build their token vocabulary.
Your task
Write shorthand(stitches, merges). Repeat at most merges times:
- Count every neighbouring pair
(tokens[i], tokens[i+1]). Overlapping pairs count separately:[a, a, a]has(a, a)twice. - Pick the pair with the highest count; on a tie, the one whose first occurrence is furthest left. If no pair appears at least twice, stop.
- Scan left to right, replacing each occurrence of that pair with one token, their concatenation. A token used in a merge cannot join another merge in the same scan.
Return the final list of tokens.
shorthand(stitches: string[], merges: int) → string[]
Examples
stitches = ["k", "p", "k", "p", "yo", "k", "p"] merges = 1
["kp", "kp", "yo", "kp"]
The pair (k, p) appears 3 times, and (p, k), (p, yo) and (yo, k) appear once each. So (k, p) is the most common pair, and merging it everywhere gives ["kp", "kp", "yo", "kp"].
stitches = ["k", "p", "k", "p", "yo", "k", "p"] merges = 3
["kp", "kp", "yo", "kp"]
After the first merge, (kp, kp), (kp, yo) and (yo, kp) each appear once, so stop early even though 3 merges were allowed.
stitches = ["k", "k", "k", "p", "k", "k"] merges = 2
["kk", "k", "p", "kk"]
The pair (k, k) is counted 3 times, at positions 0, 1 and 4. Scanning left to right, the first round merges positions 0 and 1, keeps the lone k and the p, and merges the last two k's. In the second round every pair appears only once, so the process stops.
Constraints
- 0 ≤ stitches.length ≤ 2,000
- 0 ≤ merges ≤ 100
- Each token is 1 to 10 lowercase letters.
Start with brute force
For each neighbouring pair, scan the whole list to count it, and keep the best. That is O(n²) per round: with 2,000 tokens and 100 rounds, up to 400 million comparisons.
A hash map counts every pair in one O(n) pass. Real tokenizers go further and update only the counts a merge changes.
Hints
0 of 4 shown- Hint 1
In the third example,
(k, k)is counted 3 times but only 2 merges happen. Why? - Hint 2
Counting and merging are separate passes. Counting looks at every neighbouring position. Merging walks left to right and, after a merge, skips past both tokens it used.
- Hint 3
Which structure counts every pair in one pass? If it remembers insertion order, the first-occurrence tie-break comes almost for free.
- Hint 4
Each round: one pass building a map from pair to count (in first-seen order). Take the first pair with the highest count; stop if that count is below 2. Then one pass building a new list: if the current and next token form the pair, push their concatenation and jump 2, else push the token and move 1. Key the map by the pair, not the joined string, so
(a, ab)and(aa, b)stay different.
Walkthrough and solution
Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.
How to solve it
Each round makes two linear passes. The first counts the pairs in a hash map, and the second rebuilds the list with the winning pair merged. The hard part is following the rules exactly.
Trace [k, k, k, p, k, k] with 2 merges:
- Count the pairs. (k, k) appears 3 times, and (k, p) and (p, k) appear once each, so the best pair is (k, k).
- Merge. At i = 0 the pair matches, so push "kk" and jump to 2. At i = 2 the tokens are "k" then "p", which is not the pair, so push "k". At i = 3 push "p". At i = 4 the pair matches, so push "kk". The result is [kk, k, p, kk].
- Count again. Every pair appears only once, so the process stops.
There are two easy mistakes. One is keying the counts by the joined string a + b, which lumps different pairs together, because a + ab and aa + b both spell aab. The other is forgetting to recount after each merge, since a merge creates new pairs and destroys old ones.
function shorthand(stitches, merges) {
let tokens = stitches.slice();
for (let m = 0; m < merges; m++) {
// Count adjacent pairs. A Map keeps keys in first-seen order.
const counts = new Map();
for (let i = 0; i + 1 < tokens.length; i++) {
const key = tokens[i] + ' ' + tokens[i + 1]; // space keeps pairs apart
counts.set(key, (counts.get(key) || 0) + 1);
}
let bestKey = null, bestCount = 1;
for (const [key, c] of counts) if (c > bestCount) { bestKey = key; bestCount = c; }
if (bestKey === null) break; // no pair appears twice
const [a, b] = bestKey.split(' ');
// Replace left to right; a merged pair cannot be reused.
const next = [];
for (let i = 0; i < tokens.length; i++) {
if (i + 1 < tokens.length && tokens[i] === a && tokens[i + 1] === b) {
next.push(a + b);
i++;
} else next.push(tokens[i]);
}
tokens = next;
}
return tokens;
}def shorthand(stitches, merges):
tokens = list(stitches)
for _ in range(merges):
# Count adjacent pairs. A dict keeps keys in first-seen order.
counts = {}
for pair in zip(tokens, tokens[1:]):
counts[pair] = counts.get(pair, 0) + 1
best, best_count = None, 1
for pair, c in counts.items():
if c > best_count:
best, best_count = pair, c
if best is None:
break # no pair appears twice
a, b = best
# Replace left to right; a merged pair cannot be reused.
merged = []
i = 0
while i < len(tokens):
if i + 1 < len(tokens) and tokens[i] == a and tokens[i + 1] == b:
merged.append(a + b)
i += 2
else:
merged.append(tokens[i])
i += 1
tokens = merged
return tokensRun your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.