How Needleman-Wunsch aligns two sequences globally

Short answer: Needleman-Wunsch computes a global alignment of two sequences by the same prefix grid as edit distance, with a substitution score and a gap penalty in place of unit costs. The corner cell is the optimum over alignments of the entire strings, including gaps at the ends. Affine gaps, which charge a cost to open a gap and a smaller cost to extend it, need three states per cell. The simple linear-gap table is O(nm) time.


What the problem actually asks

Levenshtein counts operations. Sequence alignment scores them. A match of identical residues may score +1, a mismatch −1, and a gap −2, or whatever matrix the domain supplies. The recurrence is unchanged in shape: the cell is the maximum of a diagonal step plus the substitution score, an up step plus the gap penalty, and a left step plus the gap penalty. Initialization of the first row and column charges a gap for every leading column or row, which is what makes the alignment global.

End gaps that should be free are a different initialization, used by overlap and fitting alignments. Leaving the first row at zero and still calling the result Needleman-Wunsch answers a different problem.


What the algorithm guarantees

With linear gap cost g and substitution scores s(a, b), the corner cell is the optimal global alignment score, and a traceback is one optimal alignment. Time is Θ(nm) and full-table space is Θ(nm). Two rows keep the score. Affine gaps replace each cell by three numbers: the best alignment ending in a match, in a gap in the first sequence, and in a gap in the second. The transition into a gap state pays the open cost. Staying there pays the extend cost. That table is still O(nm) time, with a larger constant.

The algorithm assumes additive scores along the alignment. It does not model RNA pseudoknots or other crossing structures. Local alignment, which may discard a prefix and a suffix, is Smith-Waterman and clamps cells at zero.


The working steps

  1. Choose a substitution score and a linear gap penalty. Set the first row and first column to the cumulative gap cost of a leading indel.
  2. For each cell, take the maximum of the diagonal plus the substitution score of the two characters, the cell above plus the gap penalty, and the cell to the left plus the gap penalty.
  3. The score of the global alignment is the corner cell.
  4. Trace back from the corner by the argmax until the origin, recording a column of symbols, a row of symbols, or a paired substitution.
  5. For affine gaps, compute the three states from each other with the open and extend costs, and trace back through states rather than through a single matrix.

Global means both strings are fully consumed. Smith-Waterman is the local variant. A unit-cost special case is Levenshtein, up to a sign that turns minimization of costs into maximization of scores. Free end gaps are an initialization change and should be named as such, because the traceback may then start at the best cell on the border rather than at the corner.


Approaches that look simpler and fail

Approach Why it fails when the first row is left at zero
Initialize borders to 0 and start traceback at the corner Leading gaps are free in the numbers and still forced in the traceback, or the corner is no longer the global optimum under the stated penalties. Global alignment charges the borders.
Use one cell per prefix with an affine formula stuffed into a single recurrence An affine cost depends on whether the gap is already open. One state cannot tell a new gap from a continuation. Three states can.
Maximize the score and also report the Levenshtein distance from the same cell The cell is a score under the chosen matrix, not an edit count, unless the matrix was chosen to be unit cost.
Expect the alignment to ignore a noisy prefix A noisy prefix is still aligned, possibly as a run of gaps or mismatches. Local alignment is the algorithm that may drop it.

Local alignment is Smith-Waterman. Unit edit distance is Levenshtein. Needleman-Wunsch is the global scored alignment, with an affine-gap upgrade when opening a gap should cost more than extending it.


A working example

This Python fragment aligns two sequences globally. A gap on the border is charged, and a match scores 1. CAT against CT has an optimal score of 1.

def nw(a, b):
    n, m = len(a), len(b)
    dp = [[0] * (m + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        dp[i][0] = -i
    for j in range(1, m + 1):
        dp[0][j] = -j
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            score = 1 if a[i - 1] == b[j - 1] else -1
            dp[i][j] = max(dp[i - 1][j - 1] + score, dp[i - 1][j] - 1, dp[i][j - 1] - 1)
    return dp[n][m]

assert nw("CAT", "CT") == 1
print(nw("CAT", "CT"))

Where it is used

EMBOSS needle and other sequence tools align two proteins or DNA strings globally with Needleman-Wunsch. The grid is the edit distance with a substitution score. BLAST is the heuristic a search of a whole database uses instead of this quadratic grid.


When you can drop this algorithm

Drop the single-matrix form when gaps are affine. Use three states. Drop the global recurrence when the biologically meaningful alignment is local. Keep Needleman-Wunsch when both sequences must be aligned from end to end under an additive score.


Why this stays published

We publish this so a search for Needleman-Wunsch returns the scored global recurrence and the three-state upgrade for affine gaps. Needleman-Wunsch computes an optimal global alignment in O(nm) time by maximizing match and gap scores on a prefix grid whose borders charge leading gaps.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *