Deterministic Byte Pair Encoding
Problem statement
For this exercise, assume a corpus of lowercase ASCII words. Train a deterministic word-local byte-pair encoder and return the final tokenization of that same corpus.
- Initially, each character is one token. Each occurrence in
wordscontributes separately. - Count every adjacent pair of current tokens across all words. Overlapping pair occurrences count separately, but word boundaries are never crossed.
- Select the pair with the largest count. Break a tie by lexicographic order of the left token, then of the right token.
- In each word, scan left to right and replace every nonoverlapping occurrence of that pair with the concatenation of its two tokens. Recompute frequencies after the complete pass.
Perform at most maxMerges such iterations; stop earlier if no adjacent pair remains. Do not add word-end markers, change character case, remove duplicates or encode another corpus. Return one array of final token strings per input word, preserving word and token order.
Function
bytePairEncode(words: String[], maxMerges: int) → String[][]Examples
Example 1
words = ["low","lower","low"]maxMerges = 1return = [["lo","w"],["lo","w","e","r"],["lo","w"]]The pair (l,o) occurs three times, tied with (o,w), and wins lexicographically; each lo is merged.
Example 2
words = ["aaa"]maxMerges = 1return = [["aa","a"]]Both adjacent (a,a) occurrences are counted, but the left-to-right merge consumes only the first pair.
Example 3
words = ["ab","ab"]maxMerges = 0return = [["a","b"],["a","b"]]A zero merge budget preserves the original character tokens.
Constraints
1 <= words.length <= 200.- Every word has
1through30lowercase ASCII letters. 0 <= maxMerges <= 100.- A selected pair may have frequency one; there is no minimum-frequency threshold.