Skip to main content

Implement one merge step of byte-pair encoding training: given words split into symbols with their counts, find the most frequent adjacent pair and merge it everywhere. For example, with low 5, lower 2, newest 6 and widest 3, the pairs (e, s) and (s, t) both appear 9 times, and merging (e, s) turns newest into n e w es t.

Coding rounds · Intermediate 3

Short answer

Count every adjacent symbol pair inside each word, weighted by the count of the word. Pick the pair with the highest total, with a fixed rule for ties. Rewrite each word by scanning left to right and joining that pair into one new symbol. Add the merge to the ordered merge list. One step costs O(total symbols).

Deeper answer

Clarify first: the corpus is already split into words, each word is a sequence of symbols that starts as characters or bytes, and each word has a count. Pairs never cross a word boundary.

Count the pairs: for each word and each neighbouring pair (a, b) in it, add the count of the word to counts[(a, b)]. Take best = max(counts, key=counts.get), with a fixed tie rule such as first seen. Then rewrite every word with a left-to-right scan: if the current symbol and the next one equal best, output the joined symbol and skip two positions, otherwise output one symbol and move one position. Append best to the merge list, because encoding new text later replays the merges in the same order.

Test the worked example. Also test the word a a a with the pair (a, a): it must become aa a, one merge, not two overlapping ones. Interviewers watch for counting each word once and ignoring its count, for merges across word boundaries, and for string replace on joined text, which can match in the wrong places.

What a strong answer covers

Answer it out loud in the mock interview about 3 min

Follow-ups to expect

Common mistakes

Learn it

Tokens and the context window

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.