Skip to content
Tech Interview Prep home
Technical interview guide

Sequence Alignment (Needleman-Wunsch, Smith-Waterman, BLAST)

The algorithms for comparing DNA, RNA, and protein sequences — global vs. local alignment, and the heuristics that make searching billions of bases practical.

Read
47 min
Practice MCQs
25
Interview QA
25
Edition
v7
Editorial status
Reviewed

Scope: Needleman-Wunsch and Smith-Waterman algorithms; NCBI BLAST+ documentation and statistical guidance; BLOSUM and PAM source publications reviewed 2026-09-04.

Overview

Curated: · Written: · Reviewed:

Alignment is a model-based claim about biological correspondence

Sequence alignment arranges residues to propose which positions correspond through common ancestry, conserved structure or a search objective. An alignment is not ground truth. It is the optimum or a high-scoring result under a scoring model, gap model, algorithm, input representation and search space. Biological interpretation must keep those assumptions visible.

Global alignment compares sequences end to end and is appropriate when they are expected to be homologous across most of their lengths. Needleman-Wunsch dynamic programming finds an optimum under its recurrence and boundary conditions. Local alignment finds the best matching subsequences and is useful for shared domains, motifs or fragments; Smith-Waterman resets negative scores to zero and traces back from the highest-scoring cell.

Dynamic programming works because an optimal alignment can be decomposed into optimal prefix alignments. A simple matrix stores the best score for prefixes of two sequences, giving quadratic time and space. Linear-space traceback algorithms and banding reduce resources under additional constraints. A narrow band can miss the true optimum when insertions, deletions or divergence move the path outside it.

Scoring expresses a hypothesis about evolution or similarity. Nucleotide match and mismatch scores should reflect expected divergence and composition. Protein substitution matrices give positive or less-negative scores to substitutions observed more often than chance. BLOSUM matrices are derived from conserved blocks at different clustering thresholds; PAM matrices extrapolate accepted point mutations across evolutionary distance. Matrix number conventions differ, so “higher means closer” cannot be transferred blindly between families.

Gaps model insertion and deletion events. A linear penalty charges every gap residue equally. An affine model charges gap opening more than extension, reflecting that one multi-residue indel is generally more plausible than many independent events. It requires separate dynamic-programming states for match, gap in one sequence and gap in the other. Terminal-gap policy changes whether an overlap, semiglobal or strict global result is preferred.

Multiple optimal alignments can share one score. Traceback tie-breaking can therefore change the displayed alignment without changing optimality. Report score and parameters, and avoid treating one gap placement in a repetitive region as uniquely supported. Ambiguous residues, lowercase masking and sequence alphabet must be handled explicitly.

BLAST is a heuristic database search, not exact Smith-Waterman over the entire database. It identifies high-scoring seeds, extends promising matches and uses statistical calibration to report local alignments efficiently. Sensitivity and runtime depend on program, word size, scoring matrix, gap penalties, filters, database, query composition and thresholds.

Choose the BLAST program from the biological question: nucleotide against nucleotide, protein against protein, translated nucleotide against protein, protein against translated nucleotide, or translated nucleotide against translated nucleotide. Translation expands frames and compute but detects coding similarity obscured at the nucleotide level. Query and database orientation are not interchangeable operational details.

An E-value estimates how many alignments with at least the observed score are expected by chance in a search of that size under the model. Smaller is stronger evidence, but significance is not identity, homology direction, function or orthology. E-values depend on effective search space; the same local alignment can receive a different E-value against a larger database. Bit scores normalize raw scores for the scoring system and are more comparable across searches.

Percent identity must be read with alignment length, coverage, gaps and complexity. Ninety percent identity over ten residues is different evidence from ninety percent across a full protein. Query coverage and subject coverage answer different questions. Low-complexity and repetitive sequence can generate misleading high scores, so masking reduces spurious seeds while potentially hiding genuine biology.

Database composition and version are part of the result. A hit absent today may appear after a database update; taxonomic contamination or mislabeled records can produce confident false interpretation. Record database name, release or build date, sequence counts, taxonomy filters and exact command. Preserve stable accessions with versions rather than relying on mutable display names.

Reciprocal best hits are a useful heuristic for candidate orthologs but fail with gene duplication, loss, incomplete databases and unequal evolutionary rates. Homology is a relationship of common ancestry and is not a percentage. Function transfer requires domain architecture, conserved catalytic residues, coverage, taxonomy, experimental evidence and awareness of paralogy.

Production workflows validate input alphabet and identifiers, pin tool and database versions, retain command lines and checksums, use bounded parallelism, distinguish no-hit from failure and parse structured output rather than screen text. Test known positives, shuffled negatives, edge cases, repeats, very short sequences, large gaps and alternative scoring parameters.

The production invariant is interpretability: every reported correspondence and significance claim can be traced to exact sequences, algorithm, score and gap parameters, database and version, filters, search space and deterministic parsing, with limitations stated before biological conclusions.

A check that catches the usual interview error: the same local protein alignment scored 412 bits in both of two searches. Against nr, with an effective search space of about 3.2e12, E is about 3e-112, since E is roughly the search space divided by 2^412. Against a 12 Mb custom genome the search space is far smaller. Six-frame translation makes that database about 24e6 residues rather than 12e6 letters — counting DNA bases as protein letters is its own error — so with the same 510-residue query the search space is 510 x 24e6 = 1.2e10 and E falls to about 1.2e-114. Use one definition of search space on both sides: nr's 3.2e12 is that same query against an effective database of roughly 6.3e9 residues. Bit score held; E-value moved because search space moved. Ninety-two percent identity over 38 residues is not 92% over a 510-residue query. Pin BLAST+ version, database date, matrix, gap costs and the command; without those the correspondence is not a result.

Worked example: filling a Needleman-Wunsch matrix by hand

Align GATTACA against GATCA with match +1, mismatch -1, gap -2. Each cell takes the best of three moves: diagonal (align the two characters), up (gap), left (gap).

-GATCA
-0-2-4-6-8-10
G-21-1-3-5-7
A-4-120-2-4
T-6-3031-1
T-8-5-2120
A-10-7-4-103
C-12-9-6-301
A-14-11-8-5-21

The cell at row T, column T takes max(diagonal 2+1, up 0-2, left 0-2) = 3. The final score is 1, and traceback from the bottom-right corner gives:

  G A T T A C A
  G A T - - C A     five matches, two gaps: 5(+1) + 2(-2) = 1

The optimum is not unique here. GA-T-CA scores 1 as well, on five matches and two gaps, and a traceback that prefers a different move when two are tied will return it instead. Ties are the normal case rather than a curiosity, which is why an implementation has to fix a tie-breaking order and why two correct aligners can disagree on the alignment while agreeing on the score.

Three properties follow from the recurrence and are worth stating precisely. The matrix is O(mn) in time and space, so aligning two 3,000,000-base sequences would need 9 x 10^12 cells, which is why nobody runs Needleman-Wunsch on genomes. Changing the initial row and column from the -2, -4, -6 gradient to all zeros and taking max(0, ...) at every cell turns this into Smith-Waterman, which finds the best local alignment instead of forcing a global one. And BLAST does neither: it seeds on short exact matches and extends them, trading the optimality guarantee for a database search that runs in milliseconds rather than days.