In this article
  1. Before you start
  2. Why interviewers ask this
  3. Beam search from first principles
  4. Worked example
  5. Trade-offs and edge cases
  6. How to answer it in an interview
  7. Common mistakes
  8. Follow-up questions
  9. Sources

Before you start

Why interviewers ask this

Beam search is the standard test of whether you understand that generating text is a search problem, not a lookup. A candidate who says "the model picks the most likely word" has described greedy decoding and nothing else. An interviewer then asks what goes wrong, and the answer separates levels. A weak answer repeats the definition. A strong answer explains why the best first token does not always start the best sentence, why the score needs a length correction, and why chat models usually do not use beam search at all.

The question appears in machine learning (ML) coding rounds, where the prompt is often "implement beam search", sometimes with a length penalty, and in design rounds on translation, speech and captioning. The ML coding round guide places it among the other from-scratch questions.

Beam search from first principles

Beam search is a decoding algorithm that keeps the B most probable partial output sequences at each step, extends each by every possible next token, and prunes back to B, then returns the best finished sequence.
Beam width
The beam width is the number B of partial sequences, called beams, that beam search keeps alive after each step; a width of one is greedy decoding.
Length penalty
A length penalty is a divisor applied to a sequence's log probability so that sequences of different lengths can be compared fairly, because every extra token otherwise lowers the score.

In plain words

Imagine finding a route through a town where every junction has several roads. Greedy decoding always takes the road that looks best right now. Beam search sends B scouts instead. After each junction it keeps the B scouts that are doing best and calls back the rest. The analogy breaks in one place. Real scouts see the road ahead. A language model scores only the path already walked, so a good start can still lead nowhere.

Stated precisely, beam search chooses the output sequence with the highest total log probability, searching only a narrow band of the possible sequences. Greedy decoding is the special case where the band holds one sequence. The Hugging Face documentation says greedy search "selects the next most likely token at each step" and that beam search "can look ahead" and pick a sequence with a higher overall probability even if its first tokens had lower probability (Hugging Face, read October 2026).

Step 1: Start with one empty beam

The first step sets up the search with a single beam that holds no tokens and a score of zero. The input is the prompt, or, in a translation model, the encoder's summary of the source sentence. The output is a list with one entry. The score is a log probability.

A log is used because the probability of a sequence is the product of many numbers below one, and a product of twenty such numbers can underflow, while a sum of logs stays well behaved. In Sutskever et al., the decoder "maintains a small number B of partial hypotheses, where a partial hypothesis is a prefix of some translation" (Sutskever et al., 2014). What you now know: the beam list starts with one empty entry.

Step 2: Expand every beam by every token

The second step asks the model for next-token probabilities once per beam and creates one candidate for every token in the vocabulary. The input is B beams; the output is B times V candidates, where V is the vocabulary size. Each candidate's score is its parent's score plus the log probability of the new token. Sutskever et al. describe the same move: "we extend each partial hypothesis in the beam with every possible word in the vocabulary" (Sutskever et al., 2014). This step is where the cost sits, since the model runs B times per step instead of once. What you now know: one step turns B beams into many scored candidates.

Step 3: Score all candidates together and keep the top B

The third step ranks all candidates from all beams in one list and keeps only the best B. The input is the full candidate list; the output is a new beam list of size B. The ranking is global: two children of one strong parent can both survive while a weaker parent loses all its children. The same paper says the decoder discards "all but the B most likely hypotheses according to the model's log probability" (Sutskever et al., 2014). This pruning is why the search is approximate: a sequence pruned at step three is gone, even if it would have won at step ten. What you now know: the beam never grows past B.

Step 4: Normalise the score for length

The fourth step handles beams that have ended with an end-of-sequence token, and it fixes a bias. A finished sequence leaves the beam and joins a set of complete hypotheses. Their scores cannot be compared raw, because each token adds a negative number, so a short sequence tends to score higher.

Wu et al. state that without length normalisation "regular beam search will favor shorter results over longer ones on average" (Wu et al., 2016). They divide the log probability by a length penalty, lp(Y)=(5+|Y|)α/(5+1)α, where |Y| is the number of tokens in the sequence and alpha sets the strength (0 means no penalty), and report that a value of alpha between 0.6 and 0.7 was usually best on their development set, the held-out examples used to compare settings. In the worked example below, this division reverses a ranking. What you now know: the final choice is made on normalised scores.

Step 5: Stop and return the best finished sequence

The fifth step decides when to stop and which sequence to return. The search stops when it reaches a maximum length or when the best finished hypothesis can no longer be beaten by any beam still running. The output is the finished sequence with the best normalised score, not the beam that happens to be first. Wu et al. add a pruning rule that ends the search quickly once a good finished sequence exists, which sped up their central processing unit (CPU) search by 30 to 40 percent (Wu et al., 2016). Libraries expose this choice as an early-stopping option. What you now know: the answer is the best of the finished sequences.

Beam search expands every beam and prunes back to BFive steps of beam search: start with one empty beam, expand every beam by every token, keep the top B candidates, normalise finished scores for length, and return the best finished sequence.Startone emptybeamExpandB times VrepeatKeep topBpruneNormaliselengthpenaltyReturnbestfinishedDiagram: Interview Clozo, CC BY 4.0 ·interview.clozo.ai/blog/beam-search.html

Every step expands all B beams by every token, then discards back down to B.CC BY 4.0 — source: Beam search explained: how it works, and when it beats greedy decoding
Step-by-step description
  1. One empty beam with score zero.
  2. Every beam gets every next token.
  3. Rank all candidates together and prune.
  4. Divide finished scores by the length penalty.
  5. The best finished sequence wins.
  • Beam search starts with one empty beam.
  • Rank all candidates together and keep the best B.
  • Divide finished scores by a length penalty.

Knowing it is half the job. Saying it is the other half.

Interview Clozo is an AI interview copilot for real interview rounds: it hears the question and puts a strong answer on your screen, and you say it in your own words. See the features or how it works.

Start Free Trial →

Worked example

A hand-written toy model shows greedy decoding losing to a beam of two. The model has a vocabulary of a few words and gives each next-token probability from a fixed table (illustrative: these are not measurements of a trained model). Sequences are three tokens long. At the start the model gives "the" 0.5, "a" 0.4 and "one" 0.1. After "the" its best next word is "cat" at 0.4, and after "a" it is "cat" at 0.9.

Greedy decoding takes "the" because 0.5 beats 0.4, then "cat" at 0.4, then "sat" at 0.6, for a total probability of 0.12. Beam search with width two keeps both "the" (0.5) and "a" (0.4). At step two the best candidate is "a cat" at 0.36, ahead of "the cat" at 0.2, and "a cat sat" finishes at 0.252. The best of all 16 possible sequences is also "a cat sat", so a width of two finds the optimum here, and a width of three changes nothing.1

A beam of two finds a better sequence than greedy searchBars of the probability of the best sequence found in a toy model: greedy search 0.12, beam width 2 and 3 and exhaustive search all 0.252.Best sequence probability00.10.20.3GreedyWidth 2Width 3ExhaustiveSearch method (illustrative toy model)0.120.2520.2520.252Diagram: Interview Clozo, CC BY 4.0 ·interview.clozo.ai/blog/beam-search.html
A width of two already finds the best sequence in the toy model that greedy search misses.CC BY 4.0 — source: Beam search explained: how it works, and when it beats greedy decoding
Text description of the diagram
  • Greedy decoding gives a total probability of 0.12.
  • The best of all 16 possible sequences is also "a cat sat".

The trace below shows the width-two run itself. At step one the beam keeps "the" at 0.5 and "a" at 0.4 and prunes "one" at 0.1. At step two the beam keeps "a cat" at 0.36 and "the cat" at 0.2. At step three it ends with "a cat sat" at 0.252 against "the cat sat" at 0.12.1

A width-2 beam keeps two sequences and prunes the restTrace of beam search with width two on the toy model: step one keeps 'the' at 0.5 and 'a' at 0.4 and prunes 'one'; step two keeps 'a cat' at 0.36 and 'the cat' at 0.2; step three finishes with 'a cat sat' at 0.252 ahead of 'the cat sat' at 0.12.the0.5 kepta0.4 keptone0.1 prunedthe cat0.2 kepta cat0.36 keptthe cat sat0.12a cat sat0.252 bestDiagram: Interview Clozo, CC BY 4.0 ·interview.clozo.ai/blog/beam-search.html

At width two the beam drops 'one' at step one and still ends with 'a cat sat', which greedy decoding never reaches.CC BY 4.0 — source: Beam search explained: how it works, and when it beats greedy decoding
Step-by-step description
  1. 'the' and 'a' survive; 'one' is pruned.
  2. 'a cat' 0.36 and 'the cat' 0.2 are the top two.
  3. 'a cat sat' 0.252 beats 'the cat sat' 0.12.
  • At step one the beam keeps "the" at 0.5 and "a" at 0.4 and prunes "one" at 0.1.
  • At step two the beam keeps "a cat" at 0.36 and "the cat" at 0.2.
  • At step three it ends with "a cat sat" at 0.252 against "the cat sat" at 0.12.

The length penalty can be shown with two finished sequences, again illustrative. A short one of two tokens has probability 0.30 and a longer one of five tokens has probability 0.25. On raw log probability the short one wins, at minus 1.204 against minus 1.386. With the penalty above and alpha of 0.6, the penalty is 1.097 for two tokens and 1.359 for five, so the normalised scores are minus 1.098 and minus 1.020, and the longer sequence wins.1

In the toy model a beam of width two finds the best of 16 sequences that greedy decoding misses, and the length penalty reverses the short-versus-long ranking.
FactValue
Greedy decoding result"the cat sat", probability 0.12
Beam width 2 result"a cat sat", probability 0.252
Beam width 3 result"a cat sat", probability 0.252
Best of all 16 sequences"a cat sat", probability 0.252
Short sequence, raw log probabilityminus 1.204
Long sequence, raw log probabilityminus 1.386
Short sequence, normalised (alpha 0.6)minus 1.098
Long sequence, normalised (alpha 0.6)minus 1.020

The size of the problem explains why a narrow beam is needed at all. For an illustrative vocabulary of 32,000 tokens and an output of 20 tokens, there are about 10 to the power 90 possible sequences, and a beam of width four scores 128,000 candidates per step instead.1

Trade-offs and edge cases

A wider beam is not always better. Beam search maximises probability, and for open-ended text the most probable text is often poor. Holtzman et al. report that "maximization-based decoding methods such as beam search lead to degeneration", meaning output that is "bland, incoherent, or gets stuck in repetitive loops" (Holtzman et al., 2019). Their experiments show that for the two largest models they tested, with 774 million and 1.542 billion parameters, a beam of 64 or more prefers to stop generating straight after the given context. They also note that for tasks like translation, where the output is tightly scoped by the input, repetition and genericness are less of a problem.

A second case is the cost. Each step runs the model once per beam, so compute and memory grow with B. Each beam also needs its own attention cache, so beam search multiplies cache memory as well as compute; the key-value (KV) cache page explains what that cache holds. Sutskever et al. found that "a beam of size 2 provides most of the benefits of beam search" on translation (Sutskever et al., 2014), and Wu et al. kept 8 to 12 hypotheses but saw only slight losses with 4 or 2 (Wu et al., 2016).

A third case is what beam search actually optimises. Meister et al. argue it is the exact solution to a different objective, one that pushes text toward an even spread of information across the sentence, and in their translation experiments, adherence to that objective correlated with translation quality scores (Meister et al., 2020). Reported practice differs on the best setting, so treat beam width and the penalty as settings you tune on held-out examples.

Greedy decoding is cheapest and deterministic, beam search buys better sequence probability at a multiple of the cost, and sampling gives variety for open-ended text.
MethodCost per stepSame output every runBest use
Greedy decodingOne model runYesShort outputs, speed
Beam searchB model runsYesTranslation, speech, captioning
SamplingOne model runNoOpen-ended text, chat

For attention and decoder background, see self-attention and causal masks in decoders.

How to answer it in an interview

Interviewer asks

What is beam search, and how is it different from greedy decoding?

A strong answer

I describe it as a search problem. Greedy decoding picks the single most likely next token at each step, so an early choice can lock in a poor sentence. Beam search keeps the B best partial sequences. At each step it extends all of them by every token, scores the candidates by total log probability, and prunes back to B. It is still approximate, and it needs a length penalty, because every token lowers the score and short outputs would otherwise win. It suits translation and speech; for open-ended chat it tends to repeat itself, so sampling is the usual choice.

The spoken structure is: say what greedy does wrong, say what the beam keeps, then name the length penalty and the use case.

Common mistakes

  1. Calling beam search exact. (wrong) "Beam search finds the most likely sequence." (right) "Beam search searches a narrow band, so it can miss the best sequence; a wider beam usually makes that less likely, though not always."
  2. Forgetting the length penalty. (wrong) "Pick the beam with the highest log probability." (right) "Compare finished sequences after dividing by a length penalty, or short ones win."
  3. Assuming a bigger beam is always better. (wrong) "Set the beam to 100." (right) "Past a small width the gain is tiny, the cost grows with B, the result may not improve, and open-ended text can get worse."
  4. Keeping one beam per first token only. (wrong) "Run B separate greedy searches." (right) "Rank all candidates from all beams together, so one strong parent can supply several survivors."
  5. Using it for chat. (wrong) "Beam search gives the best chat answers." (right) "It optimises probability, which tends to give bland or repetitive open-ended text."

Follow-up questions

What is the difference between beam search and greedy decoding?

Greedy decoding keeps one sequence and always takes the most likely next token. Beam search keeps B sequences and can recover when a lower-probability first token leads to a higher-probability whole sequence. A beam width of one is greedy decoding, and with sampling off, the Hugging Face documentation treats num_beams=1 as greedy search (Hugging Face, read October 2026).

How do you implement beam search with a length penalty?

Keep a running list of beams (token tuple and summed log probability) and a finished list. Each step, extend every beam by every token, take the top width candidates with a heap, and move any that end in the end-of-sequence token (EOS) to the finished list with the score divided by the length penalty; stop at the maximum length, when no beam is left, or when the best finished score beats every running beam. This function ran on the toy model extended with EOS and returned "a cat sat" for widths 2 and 3 and "the cat sat" for width 1.2

import heapq, math

EOS = "</s>"

def length_penalty(n, alpha):                 # Wu et al. (2016)
    return ((5 + n) ** alpha) / (6 ** alpha)

def beam_search(next_probs, width, max_len, alpha=0.6):
    beams = [((), 0.0)]                       # running: (tokens, sum of log probs)
    finished = []                             # (normalised score, tokens)
    for _ in range(max_len):
        cands = [(lp + math.log(p), toks + (tok,))
                 for toks, lp in beams
                 for tok, p in next_probs(toks).items()]
        beams = []
        for lp, toks in heapq.nlargest(width, cands):   # top-k, no full sort
            if toks[-1] == EOS:
                body = toks[:-1]
                finished.append((lp / length_penalty(len(body), alpha), body))
            else:
                beams.append((toks, lp))
        if not beams:
            break
        if len(finished) >= width and max(f[0] for f in finished) >= \
                max(l for _, l in beams) / length_penalty(max_len, alpha):
            break                             # no running beam can still win
    else:                                     # ran to max_len: close open beams
        for toks, lp in beams:
            finished.append((lp / length_penalty(len(toks), alpha), toks))
    return max(finished)

Two details are worth saying aloud. The early-stop rule stops when no running beam, even if every later token had probability one, could beat the best finished score at the maximum length, because a running score can only fall and the penalty only grows. Libraries differ on the exact rule. Beams are closed as unfinished only when the loop runs to the maximum length, so the answer is always a finished sequence. With a real model, next_probs is a forward pass, and you do not recompute the prompt for each beam: you share the prompt's cached keys and values between beams and, after each prune, reorder the cache so every surviving beam points at its parent's entries (see KV cache).

Why sum log probabilities instead of multiplying probabilities?

A sequence probability is a product of many numbers below one, which underflows to zero in floating point for long outputs. The log of a product is the sum of the logs, which keeps the same ranking and stays in a safe range. Every log probability is zero or negative, so no extra token raises the score, and a longer sequence usually scores lower. That is the reason a length penalty is needed.

Does a larger beam always give better output?

No. A wider beam usually finds a more probable sequence, but not always: beam search is not monotonic in width, because extra candidates can push out the parent of a path a narrower beam kept. On a two-branch toy model written for this page, width 1 returns probability 0.208, width 2 returns 0.12 and width 3 returns 0.208 again.3 Higher probability is also not better text: Holtzman et al. found that very large beams made the large models stop generating straight after the prompt (Holtzman et al., 2019), and Wu et al. saw only slight losses at widths of 4 or 2 (Wu et al., 2016).

Chat needs varied, natural text, and the most probable text is bland or repetitive. Sampling, which the Hugging Face documentation says "randomly selects a token based on the probability distribution", gives that variety (Hugging Face, read October 2026). Holtzman et al. propose nucleus sampling, which samples from the smallest set of tokens holding most of the probability mass, for this reason (Holtzman et al., 2019). The wider serving picture for a large language model (LLM) is in LLM inference.

What does beam search cost in memory and compute?

Take B as the width, T as the output length and V as the vocabulary size: the model runs about T times B forward passes, and a heap selects B from B times V candidates at each step, about O(T·B·V·log B) in all. Memory grows roughly in proportion to B because each beam holds its own attention cache, which prefix sharing and cache reordering keep from growing faster. This follows from the algorithm and is not a measured benchmark; a question about "optimised memory" in a beam search implementation has this answer. Related practice questions are collected in AI engineer interview questions.

Key takeaways
  • Beam search keeps the B best partial sequences and prunes back to B at every step.
  • Greedy decoding is the special case with a width of one, and it can lock in a poor start.
  • Divide finished scores by a length penalty, or short outputs win.
  • Cost grows with B, and a small beam often gives most of the benefit.
  • For open-ended text, sampling usually beats beam search.

Sources

  1. Sequence to Sequence Learning with Neural Networks — arXiv (Sutskever, Vinyals and Le), v3 revised 2014-12-14, 10 Sep 2014
  2. Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation — arXiv (Wu et al.), v2 revised 2016-10-08, 26 Sep 2016
  3. The Curious Case of Neural Text Degeneration — arXiv (Holtzman et al.), ICLR 2020, v2 revised 2020-02-14, 22 Apr 2019
  4. If beam search is the answer, what was the question? — arXiv (Meister, Vieira and Cotterell), EMNLP 2020, v2 revised 2021-01-17, 6 Oct 2020
  5. Generation strategies (Transformers documentation) — Hugging Face (date = read date), 24 Oct 2026