Knitting Pattern Shorthand

Hardhash mapAlso known as Byte Pair Encoding (BPE) Merges

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:

  1. Count every neighbouring pair (tokens[i], tokens[i+1]). Overlapping pairs count separately: [a, a, a] has (a, a) twice.
  2. 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.
  3. 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

Example 1
Input
stitches = ["k", "p", "k", "p", "yo", "k", "p"]
merges = 1
Output
["kp", "kp", "yo", "kp"]
Why

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"].

Example 2
Input
stitches = ["k", "p", "k", "p", "yo", "k", "p"]
merges = 3
Output
["kp", "kp", "yo", "kp"]
Why

After the first merge, (kp, kp), (kp, yo) and (yo, kp) each appear once, so stop early even though 3 merges were allowed.

Example 3
Input
stitches = ["k", "k", "k", "p", "k", "k"]
merges = 2
Output
["kk", "k", "p", "kk"]
Why

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

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.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code