{"id":230,"date":"2026-11-13T12:35:17","date_gmt":"2026-11-13T04:35:17","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-needleman-wunsch-aligns-two-sequences-globally\/"},"modified":"2026-11-13T21:53:17","modified_gmt":"2026-11-13T13:53:17","slug":"how-needleman-wunsch-aligns-two-sequences-globally","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-needleman-wunsch-aligns-two-sequences-globally\/","title":{"rendered":"How Needleman-Wunsch aligns two sequences globally"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Needleman-Wunsch<\/strong> 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 <strong>O(nm)<\/strong> time.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Levenshtein counts operations. Sequence alignment scores them. A match of identical residues may score +1, a mismatch \u22121, and a gap \u22122, 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.<\/p>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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 \u0398(nm) and full-table space is \u0398(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.<\/p>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>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.<\/li>\n<li>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.<\/li>\n<li>The score of the global alignment is the corner cell.<\/li>\n<li>Trace back from the corner by the argmax until the origin, recording a column of symbols, a row of symbols, or a paired substitution.<\/li>\n<li>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.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when the first row is left at zero<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Initialize borders to 0 and start traceback at the corner<\/td>\n<td>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.<\/td>\n<\/tr>\n<tr>\n<td>Use one cell per prefix with an affine formula stuffed into a single recurrence<\/td>\n<td>An affine cost depends on whether the gap is already open. One state cannot tell a new gap from a continuation. Three states can.<\/td>\n<\/tr>\n<tr>\n<td>Maximize the score and also report the Levenshtein distance from the same cell<\/td>\n<td>The cell is a score under the chosen matrix, not an edit count, unless the matrix was chosen to be unit cost.<\/td>\n<\/tr>\n<tr>\n<td>Expect the alignment to ignore a noisy prefix<\/td>\n<td>A noisy prefix is still aligned, possibly as a run of gaps or mismatches. Local alignment is the algorithm that may drop it.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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 <code>1<\/code>.<\/p>\n\n<pre><code class=\"language-python\">def nw(a, b):\n    n, m = len(a), len(b)\n    dp = [[0] * (m + 1) for _ in range(n + 1)]\n    for i in range(1, n + 1):\n        dp[i][0] = -i\n    for j in range(1, m + 1):\n        dp[0][j] = -j\n    for i in range(1, n + 1):\n        for j in range(1, m + 1):\n            score = 1 if a[i - 1] == b[j - 1] else -1\n            dp[i][j] = max(dp[i - 1][j - 1] + score, dp[i - 1][j] - 1, dp[i][j - 1] - 1)\n    return dp[n][m]\n\nassert nw(&quot;CAT&quot;, &quot;CT&quot;) == 1\nprint(nw(&quot;CAT&quot;, &quot;CT&quot;))\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\"><strong>EMBOSS <code>needle<\/code><\/strong> and other sequence tools align two proteins or DNA strings globally with Needleman-Wunsch. The grid is the edit distance with a substitution score. <strong>BLAST<\/strong> is the heuristic a search of a whole database uses instead of this quadratic grid.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for Needleman-Wunsch returns the scored global recurrence and the three-state upgrade for affine gaps. <strong>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.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,38],"tags":[],"class_list":["post-230","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-strings"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/230","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=230"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/230\/revisions"}],"predecessor-version":[{"id":629,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/230\/revisions\/629"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=230"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=230"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=230"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}