v9.1.1
Menu

BPE Merge Step

easyFREETokenization AlgorithmsLLM 1: Foundations

Implement a single step of the Byte Pair Encoding (BPE) merge algorithm.

Given a list of tokens (strings) and a merge pair (two consecutive tokens to merge), scan through the token list and merge every adjacent occurrence of the pair into a single token.

Example:

  • Tokens: ["l", "o", "w", "e", "r"]
  • Merge pair: ("l", "o")
  • Result: ["lo", "w", "e", "r"]

Multiple occurrences should all be merged in a single pass (left to right).

Implement bpe_merge_step(tokens, pair): tokens is a list of strings and pair is a tuple of two strings. Return a new list of strings (not a joined string); the tests join it with spaces for display. When occurrences overlap (e.g. the pair ("a", "a") in ["a", "a", "a"]), the leftmost occurrence is merged first, giving ["aa", "a"].

Example

Input
l o w e r
l o
Output
lo w e r
Reasoning
  • Inputs: tokens is the current sequence of 5 single-character tokens l, o, w, e, r, and pair is the merge rule (l, o): wherever l is immediately followed by o, the two become one token.
  • Scan the adjacent positions: the neighbouring pairs are (l, o), (o, w), (w, e), (e, r). Only the first, at positions 1–2, matches the rule, so l and o are concatenated into the new token lo.
  • Everything else is copied unchanged: w, e and r are not part of a match, so they keep their order.
  • Output: a new list of 4 tokens, shown space-separated as lo w e r. Each merge shrinks the sequence by exactly one, so 5−1=45 - 1 = 4 tokens.
  • Notice: every non-overlapping match is merged in the same pass, so a b a b c with rule (a, b) becomes ab ab c. Matches are claimed left to right: for a a a with rule (a, a) the first two fuse, giving aa a.

Constraints

  • Input line 1: space-separated tokens
  • Input line 2: two tokens separated by space (the merge pair)
  • Output: space-separated merged tokens
  • Merge all occurrences in one left-to-right pass

Learn this in

More from LLM 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.