Build a Token Merger with Threshold-Based Pair Consolidation
StringsAuto-graded · 17 test casesLast updated
Tests implementation of a stateful tokenizer that learns merge operations by iteratively combining frequent adjacent pairs, then applies those rules to encode and decode text.
Build a stateful tokenizer that learns consolidation rules from text and applies them for encoding and decoding.
You will implement a function that processes a sequence of operations:
Operation: train
- Arguments:
text(string),threshold(integer) - Learns merge rules from the given text
- Initially, each character is its own token
- Repeatedly find all adjacent token pairs in the current sequence and count their occurrences
- Select the pair with the highest count that appears at least
thresholdtimes - If multiple pairs tie for the highest count, choose the lexicographically smallest pair (comparing tuples of tokens)
- Merge all non-overlapping occurrences of the selected pair from left to right into a single new token
- Stop when no pair reaches the threshold
- Returns:
null
Operation: encode
- Arguments:
text(string) - Converts text into a list of token IDs using previously learned merge rules
- Start with each character as a separate token
- Apply all learned merges in the order they were learned
- Map each resulting token to its integer ID
- For characters not seen during training, use ID
-1 - Returns: list of integers
Operation: decode
- Arguments:
ids(list of integers) - Converts token IDs back to text
- For each valid ID, retrieve its token and concatenate the characters
- For invalid IDs (negative or out of range), use
"?" - Returns: string
Token ID Assignment:
- Base character tokens receive IDs in sorted lexicographic order starting from 0
- Each newly created merged token receives the next available ID
Example Walkthrough:
For text = "abababa" with threshold = 2:
- Initial tokens:
[a, b, a, b, a, b, a] - Round 1: Pair
(a, b)occurs 3 times, pair(b, a)occurs 2 times. Choose(a, b)lexicographically. Merge to get[ab, ab, ab, a] - Round 2: Pair
(ab, ab)occurs 2 times. Merge to get[abab, ab, a] - Round 3: No pair occurs at least 2 times. Stop.
Constraints
- 1 ≤ operations ≤ 100
- 0 ≤ text length ≤ 10,000 per operation
- 1 ≤ threshold ≤ text length
- All text contains only printable ASCII characters
encodeanddecodeare only called after at least onetrain- IDs in
decodeare integers in range[-1000, 1000]
Examples
Example 1
Input: process_tokenizer_operations(['train', 'encode', 'decode'], [['abababa', 2], ['abababa'], [[0, 1, 4]]])
Output: [None, [3, 2, 0], 'ab?']
Example 2
Input: process_tokenizer_operations(['train', 'encode', 'decode'], [['banana', 2], ['band'], [[0, 1, 999]]])
Output: [None, [1, 3, -1], 'ab?']
Hints
Hint 1
For pair counting, iterate through adjacent positions and track each (left_token, right_token) tuple. Overlapping occurrences like in 'aaa' should count the pair (a,a) twice at positions 0-1 and 1-2.
Hint 2
When merging the selected pair, scan from left to right and consume both tokens whenever you find a match. This ensures overlapping matches are resolved consistently by taking the leftmost one.
Hint 3
Apply merges during encoding in the exact order they were learned during training. Each merge pass should transform the entire sequence before the next merge is applied.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution maintains three key data structures across operations:
- Vocabulary: A list of tokens, where each token is a tuple of characters. Base characters come first in sorted order, followed by merged tokens.
- Token-to-ID mapping: Maps each token tuple to its unique integer identifier.
- Merge sequence: Records each merge operation as a pair of (original_pair, merged_token) in the order learned.
Training Phase
Start by treating each character in the input text as an individual token. The training loop repeatedly:
- Count all adjacent token pairs in the current sequence
- Find the maximum count among all pairs
- If the maximum is below the threshold, stop
- Among pairs with the maximum count, select the lexicographically smallest (comparing tuples)
- Create a new token by concatenating the selected pair
- Scan left to right and merge all non-overlapping occurrences of the pair
- Record this merge operation and assign an ID to the new token
The left-to-right merging strategy ensures that when occurrences overlap (like consecutive identical pairs), we consistently take the leftmost match first.
Encoding Phase
To encode text:
- Start with each character as a separate token
- Apply each learned merge in sequence (order matters!)
- For each merge, scan the current token list and replace matching adjacent pairs
- Convert the final tokens to their IDs, using -1 for unknown tokens
Decoding Phase
To decode a list of IDs:
- Look up each ID in the vocabulary
- For valid IDs, retrieve the token (a tuple of characters) and join them
- For invalid IDs, substitute "?"
Complexity
Training:
- Let n = text length, m = number of merges performed
- Each merge iteration: O(n) to count pairs + O(n) to apply merge
- Total: O(m × n)
- In the worst case, m can approach n, giving O(n²)
Encoding:
- Let k = text length, m = number of learned merges
- Each merge pass: O(k)
- Total: O(m × k)
Decoding:
- O(number of IDs × average token length)
Space:
- O(vocabulary size + merge count + sequence length)
from typing import List
def process_tokenizer_operations(operations: List[str], arguments: List[List]) -> List:
vocabulary = []
token_to_identifier = {}
merge_sequence = []
outputs = []
for op, args in zip(operations, arguments):
if op == "train":
text_input, min_threshold = args
unique_chars = sorted(set(text_input))
vocabulary = [(c,) for c in unique_chars]
token_to_identifier = {tok: idx for idx, tok in enumerate(vocabulary)}
token_list = [(c,) for c in text_input]
merge_sequence = []
while len(token_list) > 1:
pair_counts = {}
for pos in range(len(token_list) - 1):
pair_key = (token_list[pos], token_list[pos + 1])
pair_counts[pair_key] = pair_counts.get(pair_key, 0) + 1
if not pair_counts:
break
max_frequency = max(pair_counts.values())
if max_frequency < min_threshold:
break
selected_pair = min(p for p, freq in pair_counts.items() if freq == max_frequency)
combined_token = selected_pair[0] + selected_pair[1]
updated_list = []
position = 0
while position < len(token_list):
if position + 1 < len(token_list) and (token_list[position], token_list[position + 1]) == selected_pair:
updated_list.append(combined_token)
position += 2
else:
updated_list.append(token_list[position])
position += 1
token_list = updated_list
merge_sequence.append((selected_pair, combined_token))
if combined_token not in token_to_identifier:
token_to_identifier[combined_token] = len(vocabulary)
vocabulary.append(combined_token)
outputs.append(None)
elif op == "encode":
text_input = args[0]
token_list = [(c,) for c in text_input]
for selected_pair, combined_token in merge_sequence:
updated_list = []
position = 0
while position < len(token_list):
if position + 1 < len(token_list) and (token_list[position], token_list[position + 1]) == selected_pair:
updated_list.append(combined_token)
position += 2
else:
updated_list.append(token_list[position])
position += 1
token_list = updated_list
outputs.append([token_to_identifier.get(tok, -1) for tok in token_list])
elif op == "decode":
id_list = args[0]
reconstructed = ""
for identifier in id_list:
if isinstance(identifier, int) and 0 <= identifier < len(vocabulary):
reconstructed += "".join(vocabulary[identifier])
else:
reconstructed += "?"
outputs.append(reconstructed)
else:
raise ValueError(f"Unknown operation: {op}")
return outputs