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.
| Phase | Computation | Stored result |
|---|---|---|
| Initialization | Initial probability times first emission probability | Score for each state at t = 1 |
| Recursion | Maximum over previous states of score times transition, times emission | Best score and back-pointer per state |
| Termination | Maximum score over states at the final step | Probability of the best path |
| Backtracking | Follow back-pointers from the final best state | Most probable state sequence |
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 paths | Viterbi operations (about) |
|---|---|---|---|
| 2 | 10 | 1,024 | 40 |
| 10 | 50 | 10 to the power 50 | 5,000 |
| 45 | 30 | Astronomically large | 60,750 |
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.
Viterbi compared with related inference algorithms
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.
| Algorithm | Question answered | Core operation |
|---|---|---|
| Viterbi algorithm | Most probable full state sequence | Max over previous states |
| Forward algorithm | Total likelihood of the observations | Sum over previous states |
| Forward-backward algorithm | Posterior probability of each state per step | Sum in both directions |
| Baum-Welch algorithm | Model parameters from unlabeled data | Expectation maximization with forward-backward |
| Max-product belief propagation | MAP assignment on tree-structured graphs | Message passing with max |
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.
| Variant | Change to the basic method | Typical use |
|---|---|---|
| Beam search Viterbi | Keeps only the top-k states per step | Large-vocabulary speech recognition |
| List Viterbi | Returns the k best paths | Alternative hypotheses and reranking |
| Soft-output Viterbi | Adds reliability estimates per decision | Turbo and concatenated codes |
| Sliding-window Viterbi | Decodes with fixed delay on streams | Real-time communication receivers |
| Viterbi training | Uses best paths to re-estimate parameters | Fast approximate HMM training |
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.