← Questions

Apply ordered token merges to a string

0

A coding interview question asked at Perplexity. It tests tokenization, linked list and hash map.

Many language models read text as a list of token ids. In this scheme, every token after the single characters is built from two earlier tokens, and turning text into ids means applying those merges in order.

Implement:

def tokenize(text: str, alphabet: list[str]) -> list[int]

A token's id is its index in alphabet.

  • Start. The first entries of alphabet are single characters, one per distinct character. Every entry after them has two or more characters. Replace each character of text with the id of its single-character token. Raise ValueError if a character has no token.
  • Merges. Go through the multi-character tokens in alphabet order. For token t with id i, scan the current id sequence left to right. Wherever two adjacent ids x, y spell t (alphabet[x] + alphabet[y] == t), replace the pair with i and continue scanning after the new token. Matches do not overlap.
  • A token may split into two earlier tokens in more than one way; any such split counts. A token that cannot be written as two earlier tokens never matches and is skipped.
  • Return the id sequence after the last token has been processed.

Example 1

text = "abcab", alphabet = ["a", "b", "c", "ab", "bc", "abc", "cab"]

step sequence (as strings)
start a b c a b
ab (3) ab c ab
bc (4) no adjacent b, c left; unchanged
abc (5) abc ab (ab + c)
cab (6) unchanged

Result: [5, 3].

Example 2

text = "aaa", alphabet = ["a", "aa"] returns [1, 0]. The scan is left to right and matches do not overlap.

Constraints

  • 0 <= len(text) <= 10^5; 1 <= len(alphabet) <= 10^4; entries are distinct and at most 32 characters long.
  • Start with a straightforward solution, then make it fast when most merges touch only a small part of the text. State the time and space complexity.

Clarifying questions

  • Is the single-character prefix of alphabet exactly the set of characters in text, or can it hold extra characters that never appear?
  • When a token can be split into two earlier tokens in several ways, should every split be checked on each merge pass?
  • After a pair merges, may the new token pair with the token to its left within the same pass, or does the scan only move forward?
  • Is the empty string valid input, and should it return []?
  • How long can tokens get relative to the text: is 32 characters a hard limit I can rely on?

What a strong answer covers

  • A correct baseline first: for each multi-character token, precompute its valid (x, y) splits, then make one left-to-right pass over the current sequence. That is O(len(alphabet) * len(text)) time.
  • The faster version keeps the sequence as a doubly linked list and an index from each adjacent id pair to its positions, so a merge visits only the places where its pair occurs and updates the pairs of the neighbors it touches.
  • Preserves the left-to-right, non-overlapping rule when a pair repeats (a a a with aa gives [aa, a]), including after a linked-list splice.
  • Skips tokens that have no split into two earlier tokens, and raises ValueError for a character with no single-character token.
  • Tests: the two examples, empty text, runs of one character, a token with two different splits, and a randomized comparison of the fast version against the baseline.

Follow-ups

  • Go the other way: decode an id sequence back to text, and check that encode then decode returns the original string.
  • Train the merges: given a corpus, build the alphabet by repeatedly merging the most frequent adjacent pair.
  • Tokenize a stream of text that arrives in chunks without retokenizing everything already seen.
  • Tokenize many independent documents in parallel, and say what is shared between workers.

Where it's asked

What it tests

tokenization · linked list · hash map · simulation

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding