364. Encode a word with ranked BPE merges
Why it matters tiktoken and Hugging Face tokenizers encode every prompt with this loop.
Applying a trained BPE vocabulary means repeatedly merging the adjacent pair with the best (lowest) rank.
Write bpe_encode(word, ranks). Start with the list of characters. While any adjacent pair is in ranks (a dict from (a, b) to rank), find the pair with the lowest rank and merge every non-overlapping occurrence of it, scanning left to right. Return the final list of tokens.
def bpe_encode(word, ranks)Example 1
Input: bpe_encode("aaab", {("a", "a"): 0, ("aa", "b"): 1}) merges to ["aa", "a", "b"] first, then no "aa"+"b" pair
Output: adjacent
Explanation: So the answer is ["aa", "a", "b"].
Example 2
Input: word = 'lower', ranks = {('l', 'o'): 0, ('lo', 'w'): 1, ('e', 'r'): 2, ('low', 'er'): 3}
Output: ['lower']
Example 3
Input: word = 'xyz', ranks = {('a', 'b'): 0}
Output: ['x', 'y', 'z']
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Each round, compute the min-rank pair, then rebuild the list merging it greedily from the left.
Hint 2
Collect every adjacent pair that has a rank.
Hint 3
Merge the lowest-rank pair everywhere, left to right.
Hint 4
Repeat until no ranked pair is left.
Common mistakes
- Merging by position instead of rank.
- Merging overlapping pairs such as 'aaa' into two 'aa'.
Understand the idea
A trained BPE tokenizer is a list of merges in the order they were learned, so each pair has a rank (lower means learned earlier). To encode a word, start from single characters and keep merging the adjacent pair with the lowest rank until no known pair is left.
word 'lower', ranks {('o', 'w'): 0, ('e', 'r'): 1, ('l', 'o'): 2, ('ow', 'er'): 3}. Start [l, o, w, e, r]. Known pairs are lo (2), ow (0), er (1); the lowest is ow, giving [l, ow, e, r]. Now pairs: l-ow unknown, ow-e unknown, er (1), so merge er: [l, ow, er]. Next ow-er (3) merges: [l, ower]. l-ower is unknown, so stop. Merging the leftmost known pair (lo) first would give a different and wrong result.
loop: among adjacent pairs present in ranks, pick the lowest rank; scan left to right and merge every non-overlapping occurrence of that exact pair; repeat until no adjacent pair is in ranks
Used in: GPT-2, tiktoken and most LLM tokenizers at inference time.
Shapes and data flow
['l','o','w','e','r'] -> lo -> low -> er -> ['lower']
Topics
Companies3
- Anthropic a candidate reported this question Coding Exercises & ML System Design: Real AI Interview Questions (landedjobs)
- Mistral the topic appears in interview reports Mistral AI Interview Guide 2026: European Frontier Lab, Open-Weight Strategy, MoE, and La Plateforme
- OpenAI a candidate reported this question Coding Exercises & ML System Design: Real AI Interview Questions (landedjobs)
From public interview reports and guides. Not affiliated with or endorsed by these companies.