Skip to main content

Implement beam search: given a function that returns next-token probabilities for a partial sequence, return the most likely sequence found with a given beam width. For example, if the first token is A with 0.6 or B with 0.4, the best token after A has 0.5, and C after B has 0.9, then greedy search ends at 0.30 and a beam of width 2 finds B C at 0.36.

Coding rounds · Intermediate 3

Short answer

Keep the best B partial sequences, each with a score that is the sum of its log probabilities. Each step, extend each one with every token, add the log probability of that token, and keep the top B of all candidates. Move sequences that reach the end token to a finished list. Cost is O(T * B * V).

Deeper answer

Clarify first: the model call takes a prefix and returns a probability for each of V tokens. Ask for the beam width B, the maximum length T, the end token.

Start with one beam: the empty sequence with score 0. At each step, for every live beam get the next-token log probabilities and build the candidates (sequence + token, score + log_prob). Sort all B * V candidates and keep the best B. A candidate that ends with the end token moves to a finished list and stops growing. Stop when no live beams remain or the length limit is reached, then return the best of the finished and live sequences.

Use sums of logs, not products of probabilities, because a product of many small numbers underflows to zero. Longer sequences have lower total scores, so a fair comparison of finished sequences needs length normalisation. A width of 1 is greedy search. Test against a full listing of sequences on a tiny model. Interviewers watch for keeping only the best token per beam, and for extending finished sequences.

What a strong answer covers

Answer it out loud in the mock interview about 3 min

Follow-ups to expect

Common mistakes

Learn it

How a model picks its next word: temperature, top-p and top-k

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.