Viterbi algorithm

On this page 7

The Viterbi algorithm is a dynamic programming method that finds the single most probable sequence of hidden states given a sequence of observations, most often in a hidden Markov model (HMM). Among probabilistic models used in artificial intelligence, it is the standard decoding procedure for sequence models with discrete states, and it underpins classic speech recognition, part-of-speech tagging, gene finding and error-correcting decoders in digital communication.

Andrew Viterbi introduced the method in 1967 for decoding convolutional codes, and its structure was later recognized as a general solution to maximum a posteriori path decoding. Its key property is efficiency: instead of scoring every possible state path, which grows exponentially with sequence length, it computes the best path in time linear in the sequence length and quadratic in the number of states.

How the Viterbi algorithm decodes a hidden state sequence

The Viterbi algorithm decodes a sequence by keeping, for every state at every time step, only the best path ending there. This works because of the Markov property: the best path into state j at time t depends only on the best paths into each state at time t-1, the transition probabilities and the current observation.

The procedure runs in three phases, each with a clear role summarized below.

PhaseComputationStored result
InitializationInitial probability times first emission probabilityScore for each state at t = 1
RecursionMaximum over previous states of score times transition, times emissionBest score and back-pointer per state
TerminationMaximum score over states at the final stepProbability of the best path
BacktrackingFollow back-pointers from the final best stateMost probable state sequence
Phases of the Viterbi algorithm

Formally, the recursion defines a score as the maximum over previous states i of the previous score multiplied by the transition probability a(i, j), then multiplied by the emission probability b(j, o_t) of the current observation. The back-pointer records which i achieved that maximum, so the full path can be reconstructed at the end.

Complexity and numerical stability

The Viterbi algorithm runs in O(T × N²) time and needs O(T × N) memory for back-pointers, where T is the sequence length and N is the number of hidden states. A brute-force search would require N to the power T evaluations, which becomes infeasible even for short sequences.

The following table compares the cost of exhaustive search with the Viterbi approach for representative problem sizes.

States (N)Length (T)Brute-force pathsViterbi operations (about)
2101,02440
105010 to the power 505,000
4530Astronomically large60,750
Computational cost for typical problem sizes

Multiplying many probabilities below one quickly causes numerical underflow in floating-point arithmetic. Practical implementations therefore work in log space, replacing products with sums of log probabilities and keeping the maximum operation unchanged. This version is sometimes called the max-sum algorithm, and it gives identical paths without precision loss.

The Viterbi algorithm answers a different question from other HMM algorithms: it returns the best joint path, not the most probable state at each individual step. Confusing these objectives is a frequent source of errors in model evaluation.

AlgorithmQuestion answeredCore operation
Viterbi algorithmMost probable full state sequenceMax over previous states
Forward algorithmTotal likelihood of the observationsSum over previous states
Forward-backward algorithmPosterior probability of each state per stepSum in both directions
Baum-Welch algorithmModel parameters from unlabeled dataExpectation maximization with forward-backward
Max-product belief propagationMAP assignment on tree-structured graphsMessage passing with max
Viterbi and neighboring algorithms

The Viterbi algorithm is the special case of max-product belief propagation on a chain-structured graph. The same principle decodes linear-chain conditional random fields, where emission and transition scores come from learned feature weights rather than probabilities, and it serves as the decoding step on top of neural sequence taggers such as BiLSTM-CRF models.

Variants used in practice

Several practical variants adapt the algorithm to large state spaces, streaming data or the need for alternative hypotheses.

VariantChange to the basic methodTypical use
Beam search ViterbiKeeps only the top-k states per stepLarge-vocabulary speech recognition
List ViterbiReturns the k best pathsAlternative hypotheses and reranking
Soft-output ViterbiAdds reliability estimates per decisionTurbo and concatenated codes
Sliding-window ViterbiDecodes with fixed delay on streamsReal-time communication receivers
Viterbi trainingUses best paths to re-estimate parametersFast approximate HMM training
Common Viterbi variants

Beam pruning trades exactness for speed: if the correct path is pruned early, the decoder cannot recover it. Practitioners tune beam width on held-out data to balance accuracy against latency.

Limitations and common mistakes

The algorithm is exact only with respect to the model it is given. If transition or emission probabilities are poorly estimated, it will confidently return the best path under a wrong model.

  • Single hard answer: the output contains no uncertainty information unless a soft-output or k-best variant is used.
  • Quadratic state cost: very large state spaces require sparse transitions or pruning.
  • Path versus marginals: the Viterbi path can contain a state that is not the most probable state at that step.
  • Underflow: implementations without log-space arithmetic fail silently on long sequences.
  • Markov assumption: long-range dependencies outside the state definition are ignored.

Put simply

Imagine guessing the weather each day from what a friend did. If they went swimming, it was probably sunny. If they stayed home, perhaps it rained. You also know that sunny days tend to follow sunny days.

The Viterbi algorithm finds the most believable weather story for the whole week. It does not try every possible story. At each day, it keeps only the best story so far for each kind of weather. At the end, it traces back the winner. This makes it fast even for very long sequences.

In practice

A team building a part-of-speech tagger for legal documents trains a hidden Markov model with about 45 tags on annotated court decisions. For each sentence, the words are the observations and the grammatical tags are the hidden states. The transition table captures patterns such as determiners preceding nouns, and the emission table records how often each word appears with each tag.

When the tagger processes a 30-word sentence, the Viterbi algorithm evaluates roughly 60,000 score updates instead of an impossibly large number of tag combinations, and it returns a complete tag sequence in well under a millisecond. Ambiguous words such as “appeal”, which can be a noun or a verb, receive the tag that makes the whole sentence most probable. The team later replaces the HMM scores with a neural model but keeps Viterbi as the decoding step, because it still guarantees a consistent best tag sequence.