Skip to content
Tech Interview Prep
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.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v8
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.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-5

Derive an alignment recurrence.

Answer

Assumptions. Global alignment (Needleman–Wunsch) of A = a₁…a_m against B = b₁…b_n, linear gap penalty: a run of k gap columns costs k·d, d > 0. Substitution score s(a_i, b_j) from a fixed matrix: match +1, mismatch −1 in the trace below. Affine gaps come after.

Subproblem. F(i, j) = the maximum score over all alignments of the prefixes A[1..i] and B[1..j].

Derivation. Take any alignment of A[1..i] and B[1..j] and look at its last column. That column is one of exactly three things: a_i paired with b_j; a_i paired with a gap; or b_j paired with a gap. There is no fourth option, and the three are mutually exclusive, so the alignments partition into three disjoint classes. Deleting the last column from a class-1 member leaves an alignment of A[1..i−1] and B[1..j−1], worth at best F(i−1, j−1) + s(a_i, b_j). Class 2 leaves an alignment of A[1..i−1] and B[1..j] plus one gap column: F(i−1, j) − d. Class 3: F(i, j−1) − d. Best of the three:

F(i,j) = max( F(i−1,j−1) + s(a_i,b_j), F(i−1,j) − d, F(i,j−1) − d )

Boundaries. F(0,0) = 0; F(i,0) = −i·d; F(0,j) = −j·d. The boundary is not cosmetic: setting F(i,0) = 0 makes end gaps free, which is semi-global alignment, a different problem.

Traceback. Store a pointer per cell to whichever term attained the max (ties: diagonal first). Walk from (m,n) to (0,0); each step emits one column.

Worked trace. A = AC, B = AGC, match +1, mismatch −1, d = 2.

Fj=0AGC
i=00−2−4−6
A−21−1−3
C−4−100

F(2,3) = max(F(1,2)+s(C,C) = −1+1 = 0, F(1,3)−2 = −5, F(2,2)−2 = −2) = 0. Traceback: (2,3)←(1,2) diagonal, (1,2)←(1,1) left, (1,1)←(0,0) diagonal. Alignment A: A - C, B: A G C, score 1 − 2 + 1 = 0 = F(2,3).

Affine gaps. A run of k gaps costing o + k·e (o open, e extend) breaks the recurrence: F(i,j) cannot tell whether the gap it just opened is length 1 or 10. Gotoh's fix is three matrices: M ends with a_i against b_j, Ix with a_i against a gap, Iy with b_j against a gap:

M(i,j) = max(M(i−1,j−1), Ix(i−1,j−1), Iy(i−1,j−1)) + s(a_i,b_j) Ix(i,j) = max(M(i−1,j) − o − e, Ix(i−1,j) − e) Iy(i,j) = max(M(i,j−1) − o − e, Iy(i,j−1) − e)

Ix opens only from M, never from Iy: allowing that lets a gap switch strands without a substitution, which no alignment does.

Trade-offs. Linear: one matrix, O(mn) time, O(min(m,n)) space with Hirschberg. Affine: three matrices, ~3× constant factor, same asymptotics, and the right model whenever an indel is one event (sequencing reads, protein homologs). Local alignment (Smith–Waterman) adds a 0 term to the max and zeroes every boundary; use it when the sequences share only a domain.

Failure modes.

  • Wrong base case (F(i,0)=0): end gaps become free. Detect by aligning two sequences with no shared residue: global must return a negative score.
  • Illegal gap switching (Ix opened from Iy): double counts. Detect by brute-force enumerating all alignments for m,n ≤ 8 and comparing scores.
  • Score–traceback mismatch: recompute the traceback's score and compare to F(m,n); any disagreement means the pointer table is stale.
  • Missing state: affine scoring with only F(i,j). Detect by comparing against Gotoh on a pair with a 5-residue indel: the single-matrix version mis-penalizes it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Implement Needleman-Wunsch correctly.

Answer

Core answer. Needleman-Wunsch is global alignment by dynamic programming. Pin the scoring first, because the recurrence is only correct relative to it: assume match +1, mismatch -1, gap -2, linear gap (no affine penalty). Let F[i][j] be the best score aligning a[:i] with b[:j]. Boundaries are F[i][0] = i*gap, F[0][j] = j*gap, F[0][0] = 0: leading gaps are not free. The recurrence is

F[i][j] = max(F[i-1][j-1] + sub(a[i-1], b[j-1]), F[i-1][j] + gap, F[i][j-1] + gap)

The answer is F[m][n]. It is correct because every alignment of a[:i] and b[:j] ends in exactly one of three ways: the last characters paired, a's last character gapped, or b's last character gapped, and each case reduces to a strictly smaller prefix problem, so filling in increasing i, j visits every subproblem before it is needed. Traceback walks from (m,n) to (0,0), at each cell taking whichever predecessor produced the stored value, emitting the paired characters or a gap.

Python
# Python 3.11
def needleman_wunsch(a, b, match=1, mismatch=-1, gap=-2):
    m, n = len(a), len(b)
    F = [[0]*(n+1) for _ in range(m+1)]
    for i in range(1, m+1): F[i][0] = i*gap
    for j in range(1, n+1): F[0][j] = j*gap
    for i in range(1, m+1):
        for j in range(1, n+1):
            sub = F[i-1][j-1] + (match if a[i-1] == b[j-1] else mismatch)
            F[i][j] = max(sub, F[i-1][j] + gap, F[i][j-1] + gap)
    i, j, ra, rb = m, n, [], []
    while i > 0 or j > 0:
        if i > 0 and j > 0 and F[i][j] == F[i-1][j-1] + (match if a[i-1] == b[j-1] else mismatch):
            ra.append(a[i-1]); rb.append(b[j-1]); i -= 1; j -= 1
        elif i > 0 and F[i][j] == F[i-1][j] + gap:
            ra.append(a[i-1]); rb.append('-'); i -= 1
        else:
            ra.append('-'); rb.append(b[j-1]); j -= 1
    return F[m][n], ''.join(reversed(ra)), ''.join(reversed(rb))

Worked trace. a = "GAC", b = "GC". Filled matrix:

""GC
""0-2-4
G-21-1
A-4-10
C-6-30

F[3][2] = 0. Traceback: (3,2) diagonal (C/C), (2,1) up (A/-), (1,1) diagonal (G/G). Alignment GAC / G-C, score 1 - 2 + 1 = 0. ✓

Trade-offs. Time is O(mn), space O(mn) because traceback needs the full matrix. For long reads that dominates: two 10k sequences at 4 bytes/cell is ~400 MB. Hirschberg's divide-and-conquer gives the same alignment in O(min(m,n)) space and O(mn) time. If the sequences are similar, banded alignment restricts the DP to a diagonal band of width k, giving O(kn) time and space: the right call when you know the edit distance is small.

Failure modes, with detection.

BugSymptomDetect
Boundaries left at 0leading gaps free, score inflatedalign "AAA" vs ""; expect -6, not 0
Sign error (+gap)gaps rewardedidentical strings must score m*match
Off-by-one (a[i])shifted alignment or IndexErrorcompare against a reference on "GAC"/"GC"
Greedy traceback drops tiesonly one of several optimal alignments returnedcount optimal alignments against an enumerator
int32 overflowwrong score on long inputsm*n*match exceeds 2^31; use int64 or Python ints

Ties are the subtle one: when two predecessors give the same value, the alignment is not unique, and a fixed preference order silently picks one. That is fine for a single answer, wrong if the caller expects all optimal alignments.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Choose global versus local alignment for two proteins.

Answer

The call. First question I'd ask: are these two proteins expected to be homologous end to end, or am I looking for a shared region? If they're orthologs of comparable length and I want to know whether they correspond across their whole lengths, global: Needleman-Wunsch, EMBOSS needle, or Biopython's PairwiseAligner in global mode. If one is a fragment or a single domain, or I'm asking whether they share a motif, local: Smith-Waterman, EMBOSS water, BLASTP. Database search defaults to local because you rarely know the query is full-length and the subject isn't.

Why the boundary conditions decide it. Needleman-Wunsch seeds the first row and column with cumulative gap penalties (DP[i][0] = −i·g, DP[0][j] = −j·g) and reads the answer at DP[m][n]. Every residue of both sequences is accounted for, so a terminal extension is charged as gaps. Smith-Waterman seeds the first row and column to zero, applies max(0, …) at every cell, and takes the maximum over the whole matrix. A negative prefix is discarded rather than carried, so end gaps are free and the alignment can start and end anywhere.

Worked trace. X = MKTA, Y = KTA, match +2, mismatch −1, gap −2. Simplified linear scheme, not BLOSUM62, so the arithmetic is checkable by hand.

Global (Needleman-Wunsch):

–KTA
–0−2−4−6
M−2−1−3−5
K−40−2−4
T−6−220
A−8−404

Local (Smith-Waterman):

–KTA
–0000
M0000
K0200
T0042
A0026

Global reads 4 at DP[4][3], traceback M/gap, K/K, T/T, A/A. Local takes the max cell 6 at H[4][3], traceback K/K, T/T, A/A. Same three matched pairs; global is exactly 2 lower, and that 2 is the leading M paid as a gap. Scale to a 400-residue protein with a 60-residue N-terminal tag and global loses 60 gap penalties while local is untouched.

Failure modes, and how you catch each one.

Fragment against full-length. Global forces the missing residues into terminal gaps, so the score measures length mismatch rather than homology. Detection: measure the fraction of the shorter sequence sitting in end gaps; past roughly 20% the global score is not telling you about relatedness. Fix: local, or semi-global. EMBOSS needle with -endopen 0 -endextend 0 makes end gaps free while keeping the interior global.

Fusion or multi-domain protein. A fusion of domains A and B aligned globally to a protein carrying only A still produces a tidy end-to-end alignment, because the DP has to place B somewhere. Detection: run local and look at whether the high-scoring segments are disjoint. Two separate local alignments with a low-scoring stretch between them is the signature.

Wrong isoform. An alternative start codon or a skipped exon shifts everything downstream. Detection: compare the alignment's start and end coordinates against the annotated domain boundaries in Pfam or InterPro; if the aligned region begins 40 residues upstream of the annotated domain, you aligned the wrong isoform.

Score mistaken for significance. A global score has no E-value and is not comparable across pairs of different lengths. 40% identity over 100 residues is meaningful; 40% identity over 30 residues sits in the twilight zone and is what shuffled sequences produce. Detection: shuffle one sequence a thousand times, realign, and compare; or push the same pair through BLASTP and read the E-value, which is computed against the actual database size.

Defaults worth knowing: BLASTP uses BLOSUM62, gap open 11, gap extend 1, word size 3, E-value threshold 10. EMBOSS needle and water default to BLOSUM62 with gap open 10 and gap extend 0.5.

When to reverse the default. If the two sequences are the same length and the question is "are these the same protein", global is right: local will happily align a conserved 50-residue patch and hide the fact that the rest diverged. If the question is "do these share a domain", local is right: global buries the signal under terminal gap penalties. Both algorithms are O(mn) time; naive O(mn) space, reducible to O(min(m,n)) with Hirschberg for global or Myers-Miller for local. Two 500-residue proteins is 250,000 cells, nothing. BLASTP exists because scanning a database is millions of pairs, so it seeds on 3-residue words instead of filling the full matrix.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Implement and verify local alignment.

Answer

What I'd say first

I'd pin the scoring scheme before writing code, because "local alignment" alone is underspecified. Assume match +2, mismatch −1, linear gap −2 for the trace below; production would use affine gaps (open 11, extend 1 with BLOSUM62: BLAST's default).

Smith–Waterman recurrence, where H[i][j] is the best local alignment score ending at s1[i], s2[j]:

H[i][j] = max(0, H[i-1][j-1] + sub(s1[i], s2[j]),
                 H[i-1][j] - gap,
                 H[i][j-1] - gap)

The zero floor is the whole trick. A cell that would go negative restarts, so an optimal region is free to begin anywhere in either sequence: no penalty for the prefix you skipped. The global maximum over all cells is the best local alignment; traceback from that cell follows the max back and stops the moment it reaches a zero cell.

Worked trace: s1 = TACGG, s2 = ACG, match +2, mismatch −1, gap −2.

j=0j=1 (A)j=2 (C)j=3 (G)
i=00000
i=1 (T)0000
i=2 (A)0200
i=3 (C)0042
i=4 (G)0026
i=5 (G)0004

Max is 6 at (4,3). Traceback: (4,3) G/G → (3,2) C/C → (2,1) A/A → (1,0) is zero, stop. Alignment s1[2..4]=ACG vs s2[1..3]=ACG, score 6 = 3×2. Coordinates 1-based inclusive: query 2–4, target 1–3.

Verification: the co-equal half of the question. Compare score and coordinates against a reference implementation, not by eye. Biopython's Align.PairwiseAligner(mode="local") with the same substitution matrix and gap costs; Parasail or SSW for the SIMD path. Feed two classes of case: embedded motifs (plant a known motif in random flanks, assert the returned coordinates bracket the planted region) and negative cases (no shared substring → score 0, empty alignment, no crash). edlib is a useful cross-check only for edit distance: it doesn't do substitution scoring, so its numbers are not comparable to a Smith–Waterman score.

Trade-offs. Full DP is O(mn) time and O(mn) space; a 10 kb query against a 3 Gb genome is ~3×10¹⁰ cells, infeasible. Banded DP restricts to |i−j| ≤ k, O(kn), fine when the sequences are near-identical. BLAST seeds with k-mers (default 11 for nucleotides) and extends only hits with X-drop, trading sensitivity for speed. Parasail/SSW vectorize the anti-diagonal with SIMD for roughly an order of magnitude over scalar. Use full DP for short reads or when you need exact optimality; seeding when you need genome-scale throughput and can tolerate missed weak hits.

Failure modes and detection

  • Global-style init (first row/col set to cumulative gap penalties instead of 0): local alignment degenerates to global. Detect: the negative-case test returns a nonzero score.
  • Wrong stop: traceback runs to (0,0) instead of a zero cell, padding the alignment with leading gaps. Detect: assert the first aligned pair is a match, or watch the score drop.
  • Coordinate conversion: 0-based DP indices vs 1-based inclusive output. Detect: off-by-one on the embedded-motif test.
  • Multiple maxima: ties broken arbitrarily give nondeterministic coordinates. Detect: run twice and compare, or assert a documented tie-break.
  • Gap-state error: affine gaps need three matrices (M, Ix, Iy); collapsing to one over- or under-counts. Detect: compare against Parasail with the same open/extend.
  • Low-complexity matches: poly-A flanks score high spuriously. Detect: DUST/masking, or check the score against a shuffled-sequence null.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Choose a protein scoring matrix.

Answer

Core answer. Default to BLOSUM62 with BLAST's default gap costs, -11 open / -1 extend. That pairing is calibrated: BLOSUM62 was derived from BLOCKS by clustering sequences at 62% identity, so its target frequencies describe substitutions between sequences roughly 30–60% identical, where most homology searches land. Move off it only when you have evidence about expected identity: BLOSUM80 (-10/-1) for close homologs above ~50% identity, BLOSUM45 (-14/-2) for remote ones below ~30%. If you are hunting remote homologs and can afford the build, a profile HMM beats any single matrix because it adapts per position.

What a matrix entry is. Each score is a log-odds ratio:

S_ij = log2( q_ij / (p_i p_j) )

q_ij is the observed frequency of residues i and j aligned in the training set; p_i, p_j are background frequencies. Positive means the pair occurs more often than chance in related sequences. BLOSUM62 stores these as rounded integers in half-bits, so the W/W entry of 11 is 5.5 bits: q_WW/(p_W p_W) = 2^5.5 ≈ 45, i.e. tryptophan pairs about 45× more often than chance.

The matrix's relative entropy, expected score per aligned position, is what buys sensitivity. BLOSUM62 is about 0.7 bits/position, PAM250 about 0.36. Lower-entropy matrices tolerate more substitutions, so they find distant homologs but admit more false positives; higher-entropy ones are sharper but miss remote relatives. PAM250 is PAM1 raised to the 250th power, extrapolating a 1%-accepted-mutation model out to ~20% identity.

matrixtrainingtarget identityBLAST gap costs
BLOSUM80BLOCKS @ 80%>50%-10/-1
BLOSUM62BLOCKS @ 62%30–60%-11/-1
BLOSUM45BLOCKS @ 45%<30%-14/-2
PAM250PAM1^250~20%not a BLAST default

Worked trace. Score the ungapped alignment WYF against WFF with BLOSUM62: W/W = 11, Y/F = 3, F/F = 6, total 20 half-bits = 10 bits. The same three substitutions score differently under a lower-identity matrix, which is why raw scores are not comparable across matrices: compare E-values.

When a matrix is the wrong choice. BLOSUM62 on a target below ~20% identity is the classic miss: true homologs fall under the E-value cutoff while chance alignments still score. A known close paralog is the case for BLOSUM80, which sharpens discrimination; a remote homolog is the case for BLOSUM45 or a profile HMM.

Failure modes and how I catch them.

  • Wrong distance. Sensitivity collapses on a labelled set. Benchmark positives (SCOP superfamily pairs) against reversed or shuffled decoys and plot ROC; if swapping BLOSUM62 for BLOSUM45 lifts sensitivity at a fixed false-positive rate, you were on the wrong matrix.
  • Compositional bias. A query rich in a few residues (coiled-coil, low-complexity) scores high against unrelated proteins because p_i is wrong for that sequence. BLAST's composition-based statistics correct the score; toggle the adjustment and watch E-values shift.
  • Short query. Karlin–Altschul E-values assume a long alignment; a 30-residue peptide gives an untrustworthy E-value. Check alignment length and treat raw score, not E-value, as the signal.
  • Membrane proteins. Transmembrane stretches are hydrophobic and score spuriously; use a TM-aware matrix (PHAT, SLIM) or mask the segments.
  • Units. BLOSUM62 is half-bits in BLAST; paste those integers into a tool expecting bits and every threshold shifts by 2×. Check the tool's documented units before trusting a cutoff.
  • Mixing unsupported penalties. -11/-1 is calibrated for BLOSUM62; applying it to BLOSUM80 over-penalizes gaps. Use the tool's matrix–gap table rather than hand-picking.
  • Overinterpreting score. Raw scores are not comparable across matrices or lengths; compare E-values.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Implement affine-gap alignment.

Answer

Assume global alignment (Needleman–Wunsch), a substitution matrix (BLOSUM62 for protein, +1 match / −1 mismatch for DNA), and a gap of length L costing open + (L-1)*extend. The Gotoh three-matrix recurrence is the standard implementation.

Let M[i][j] be the best score of A[1..i] aligned to B[1..j] ending in a matched pair, Ix[i][j] ending in a gap in B (consuming A[i]), Iy[i][j] ending in a gap in A (consuming B[j]). With d = open, e = extend, s = substitution score:

M[i][j]  = max(M[i-1][j-1], Ix[i-1][j-1], Iy[i-1][j-1]) + s(A[i], B[j])
Ix[i][j] = max(M[i-1][j] - d, Ix[i-1][j] - e)
Iy[i][j] = max(M[i][j-1] - d, Iy[i][j-1] - e)

Initialization: M[0][0]=0; Ix[i][0] = -d - (i-1)*e; Iy[0][j] = -d - (j-1)*e; all other boundary cells -inf. The answer is max(M[m][n], Ix[m][n], Iy[m][n]). Traceback follows the pointer that produced each cell.

Why three states

The open penalty is charged exactly once, on the transition from M into Ix or Iy. Once inside a gap state, only e is subtracted. That is the whole point: a single matrix cannot distinguish "first gap column" from "continuation", so it either charges d every column (linear gap) or needs a second state. The Ix and Iy states never transition into each other: that would align a gap to a gap, which is meaningless and would let a gap in A and a gap in B cancel.

Trace

A = "AC", B = "A", match +1, mismatch -1, d=2, e=1.

i,jMIxIy
0,00-inf-inf
1,0-inf-2-inf
2,0-inf-3-inf
0,1-inf-inf-2
1,11-inf-inf
2,1-3-1-inf

Best is Ix[2][1] = -1, from M[1][1] - d = 1 - 2. Traceback: A–A match, then C aligned to a gap. Score 1 - 2 = -1.

Trade-offs

Linear gap (gap = L*e, one matrix) is O(mn) time and O(mn) space with a single state and no open/extension distinction. It is the right choice when gaps are short and the alignment is high-identity: DNA within a species, or when you only care about the alignment path, not the score. Affine costs three matrices, so roughly 3x memory and 3x the inner-loop work; the payoff is that a 10-residue indel is charged d + 9e instead of 10e, which is what biology actually does. If you need linear space, Hirschberg's divide-and-conquer works with Gotoh but the traceback logic gets fiddly.

Failure modes

  • Double-charging open: subtracting d in both M->Ix and Ix->Ix. Detect by scoring a known single-gap alignment by hand and comparing.
  • Illegal Ix->Iy transition: allowing it lets a gap in A and a gap in B cancel. Detect by asserting the transition is absent in the recurrence.
  • Boundary error: setting Ix[i][0] = -inf instead of -d-(i-1)e makes leading gaps free. Detect with a test where one sequence is a prefix of the other.
  • Convention mismatch: open+(L-1)*extend vs open+L*extend differ by one e per gap. Check the tool's docs; the scores shift by a constant per gap.
  • Tie handling: multiple tracebacks give the same score. Pick a deterministic order (e.g., M, Ix, Iy) so tests are reproducible.
  • Terminal penalty: free end gaps (semi-global) vs penalized (global). Decide before writing the recurrence; it changes initialization.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How does dynamic programming sequence alignment with affine gap penalties reduce its time complexity from O(n^3) to O(n^2)?

Answer

The 90-second answer. Affine gap cost is linear in gap length: a gap of length $k$ costs $d+(k-1)e$. That linearity is the whole trick. The best gap ending at a cell is either a fresh open (cost $d$) or an extension of the best gap ending at the adjacent cell (cost $e$): a Markov property, so you look back exactly one cell instead of scanning every possible gap length. Gotoh's algorithm encodes this as three matrices: $M$ (last column is an aligned pair), $I_x$ ($x_i$ against a gap), $I_y$ ($y_j$ against a gap): each cell computed from three neighbours in $O(1)$. Total $O(mn)$ time, $O(n^2)$ for equal-length sequences.

Why the naive recurrence is cubic

With $W(k)=d+(k-1)e$, a single-matrix recurrence must try every gap length:

$$M[i,j]=\max\begin{cases}M[i-1,j-1]+s(x_i,y_j)\\max_{1\le k\le i}{M[i-k,j]-W(k)}\\max_{1\le k\le j}{M[i,j-k]-W(k)}\end{cases}$$

Cell $(i,j)$ scans $O(i+j)$ predecessors, so $\sum_{i,j}O(i+j)=O(n^3)$.

The telescoping step

Define $I_x[i,j]=\max_{1\le k\le i}{M[i-k,j]-W(k)}$, the best score ending with $x_{i-k+1..i}$ aligned to a gap. Substitute $W$:

$$I_x[i,j]=\max_{1\le k\le i}{M[i-k,j]-d-(k-1)e}$$

Pull the first term out and re-index the rest with $k'=k-1$:

$$=\max\Bigl{M[i-1,j]-d,;\underbrace{\max_{1\le k'\le i-1}{M[i-1-k',j]-d-(k'-1)e}}_{I_x[i-1,j]}-e\Bigr}$$

so $I_x[i,j]=\max(M[i-1,j]-d,;I_x[i-1,j]-e)$. The $O(i)$ scan collapses to two terms. Same for $I_y$ along the row.

Gotoh's recurrences

$$\begin{aligned}I_x[i,j]&=\max\bigl(M[i-1,j]-d,;I_x[i-1,j]-e\bigr)\I_y[i,j]&=\max\bigl(M[i,j-1]-d,;I_y[i,j-1]-e\bigr)\M[i,j]&=s(x_i,y_j)+\max\bigl(M[i-1,j-1],;I_x[i-1,j-1],;I_y[i-1,j-1]\bigr)\end{aligned}$$

Boundaries: $M[0,0]=0$; $I_x[i,0]=-(d+(i-1)e)$ and $I_y[0,j]=-(d+(j-1)e)$; $M[i,0]=M[0,j]=-\infty$ for $i,j\ge1$; $I_x[0,j]=I_y[i,0]=-\infty$. (Gotoh, J. Mol. Biol. 162:705–708, 1982.)

Worked trace

$x=\text{"AC"}$, $y=\text{"AGGC"}$, match $+1$, mismatch $-1$, $d=2$, $e=1$. Init: $M[0,0]=0$, $I_y[0,1..4]=-2,-3,-4,-5$, $I_x[1,0]=-2$, $I_x[2,0]=-3$, other boundaries $-\infty$.

$(i,j)$$I_x$$I_y$$M$
$(1,1)$$-\infty$$-\infty$$1$
$(1,2)$$-\infty$$-1$$-3$
$(1,3)$$-\infty$$-2$$-4$
$(1,4)$$-\infty$$-3$$-5$
$(2,1)$$-1$$-\infty$$-3$
$(2,2)$$-5$$-5$$0$
$(2,3)$$-6$$-2$$-2$
$(2,4)$$-7$$-3$$-1$

The optimal path: $M[1,1]=1$ (A–A match) → $I_y[1,2]=M[1,1]-d=-1$ (open a gap for the first G) → $I_y[1,3]=I_y[1,2]-e=-2$ (extend it over the second G) → $M[2,4]=s(C,C)+I_y[1,3]=1-2=-1$ (C–C match). Final score $\max(M[2,4],I_x[2,4],I_y[2,4])=\max(-1,-7,-3)=-1$, i.e. $+1-(2+1)+1$. The naive scan over $k$ returns the same $-1$ but pays $O(n)$ per cell.

Complexity

ApproachDependencyOps/cellTimeSpace
Naive affineall prior cells in row $i$, col $j$$O(n)$$O(n^3)$$O(n^2)$
Gotoh 3-state$(i-1,j-1),(i-1,j),(i,j-1)$$O(1)$$O(n^2)$$O(n^2)$; $O(\min(m,n))$ score-only

Failure modes

  1. Direct $I_x\leftrightarrow I_y$ transitions. Letting $I_x[i,j]$ extend from $I_y[i-1,j]$ allows an insertion immediately followed by a deletion, charging two open penalties for what is really a substitution. Every gap state must re-enter through $M$.
  2. Boundary initialization. Row 0 and column 0 must charge $d+(k-1)e$ at index $k$ and set illegal states to $-\infty$. Setting $(0,k)$ to $-k\cdot d$, or leaving $M[i,0]$ at 0, produces phantom zero-cost gap extensions at the sequence ends.
  3. Traceback state. The final cell is $\max(M,I_x,I_y)$, not $M$ alone; recovering the alignment requires recording which state each cell came from, or the gap structure is lost.
  4. Sentinel arithmetic. A finite $-\infty$ stand-in that is too small in magnitude (e.g. $-10^9$ when real scores can reach $-10^{10}$) gets beaten by a real path and silently corrupts the result. Use a true $-\infty$ or a sentinel provably below the worst achievable score.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

How do you choose gap-open and gap-extension penalties for a given alignment task: closely related proteins, divergent homologs, or reads carrying sequencing indels, and how do those choices interact with the substitution matrix and the expected indel-length distribution?

Answer

First, fix the convention. I use BLAST's: a gap of length L costs g_o + L·g_e. Some texts write g_o + (L−1)·g_e; the two differ by g_e per gap, so state which you mean before comparing numbers.

The matrix and gap penalties are the same currency. A gap is worth taking only when it buys more match score than the mismatches it replaces. For BLOSUM62, a conservative mismatch like I/V scores +3; a bad one like W/C scores −2. With the BLASTP default g_o=11, g_e=1, a single-residue gap costs 12, more than any single mismatch, so gaps appear only when they let several residues align. That is the right bias for closely related proteins: substitutions are common, indels are rare and usually short. If you drop g_o to 5, a one-residue gap costs 6, still above most mismatches, but a two-residue gap costs 7, and now the aligner will happily gap through a region of conservative substitutions. That is the classic over-gapping failure: the alignment looks tidy but the gap is not a real indel.

The extension penalty sets the expected gap length. Under the affine model, P(gap length L) ∝ exp(−λ·g_e·L), so gap lengths are geometric with mean ≈ 1/(1 − exp(−λ·g_e)). For BLOSUM62, λ ≈ 0.267, so g_e=1 gives a mean near 4.3 residues; g_e=2 gives ~2.4; g_e=0.5 gives ~8.0. So g_e is not a free knob: it encodes the indel-length distribution you expect. If your task has long indels (a domain insertion, or ONT reads with 5–10 bp deletions) a high g_e will fragment one true gap into several short ones, or force mismatches. If your task has only point substitutions, a low g_e invites spurious long gaps.

NCBI publishes recommended gap costs per matrix, and they move together:

MatrixRecommended g_o/g_eOpen:extend
BLOSUM4514/27:1
BLOSUM6211/111:1
BLOSUM8010/110:1
BLOSUM909/19:1

Notice that the more divergent matrix (BLOSUM45) has a higher open and higher extension. That is not a contradiction: BLOSUM45 already gives low scores to mismatches, so gaps become relatively cheaper; raising both penalties restores the balance. The ratio open:extend is lower for BLOSUM45 (7:1 vs 11:1), meaning long gaps are penalized more relative to opening. Appropriate when you expect many substitutions but few long indels.

For reads, the error model is different. Illumina indels are rare (~0.1–1% per base) and short (1–2 bp). BWA-MEM defaults are -O 6 -E 1, a much lower open than BLASTP because a single sequencing indel should not cost as much as a biological indel in a protein alignment. For ONT/PacBio, indel rates are 5–15% and lengths often 1–10 bp, so aligners like minimap2 lower the open further and raise the extension (e.g., -O 4 -E 2 for ONT) to allow the indel but stop it from running. The principle is the same: match the penalty to the empirical indel-length distribution of the platform.

Failure modes to name: over-gapping from too-low g_o (detect by gap count per alignment vs. known homologs); under-gapping from too-high g_o (detect by mismatches clustering where an indel is known); matrix/penalty mismatch (using BLOSUM62 with 14/2, which is not a recommended pair and shifts the score distribution); and ignoring the length distribution (using a high g_e on long-read data, which fragments true indels). The check is always the same: align a positive set with known indels and a negative set of unrelated sequences, and look at the gap-length histogram against the one you expected.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Align a read expected to cover part of a reference end.

Answer

What I'd say first. The read is the thing with real ends; the reference overhang past it is not. So the alignment should be semi-global: end gaps on the reference (target) side are free, end gaps on the read (query) side are penalized. That is narrower than a local alignment and the opposite of a global one.

Assumptions I'd state out loud: the read is anchored. Its first and last bases are real sequence, not adapter; the reference is the longer sequence and the read is expected to sit inside it or run off one end; and I care about reference coordinates, not just the score.

Mechanism. In the DP matrix D[i][j] = best score of Q[1..i] against R[1..j], free reference end gaps mean D[0][j] = 0 for every j (skipping a reference prefix costs nothing) and traceback starts from the best cell in the last row, i = |Q|, so a reference suffix is free too. Query end gaps stay penalized, so D[i][0] = -i*g. Global alignment instead sets D[0][j] = -j*g; Smith-Waterman sets both borders to 0 and traces back from the global max, which frees the read ends as well.

Worked trace, match +1, mismatch -1, gap -1. Q = AC, R = TAC:

j=0TAC
i=00000
A-1-110
C-2-202

Traceback from the last row: max is D[2][3] = 2, from D[1][2] + 1 (C/C match), which came from D[0][1] + 1 (A/A match), which came from the free reference prefix. Result: 2M at R[2..3], score 2, leading T unpenalized. A global alignment of the same placement scores 1, because it pays a gap for that T.

In practice. BWA-MEM does local alignment, so both read ends can be soft-clipped; -L sets the 5'/3' clipping penalty (default 5,5) and -T the minimum output score (default 30). Soft clips stay in SEQ and appear as S in CIGAR; hard clips (H) remove the bases and show up in supplementary records. POS is 1-based and points at the first reference-consuming CIGAR op, so a leading 10S does not move POS. A 100 bp read covering the left end of a contig can come back as 90M10S with POS at the contig start.

When free end gaps backfire. If the read genuinely should be anchored at both ends (an amplicon, or a panel where the primer is trimmed) free target end gaps let a read slide off the reference end and still score well. That is how paralogous or repeat reads land on the wrong contig. The deciding question is whether the reference overhang is biological (free it) or the read is supposed to be fully contained (penalize it).

Failure modes and how I'd catch them.

  • Free end on the wrong sequence: the read clips instead of the reference. Check which side carries the S/H, and whether the clipped bases match adapter (fastp, cutadapt) or real sequence.
  • Truncation hidden as clipping: a 40 bp soft clip on a 150 bp read looks like a clean end. Compare clip length to expected read length, and check MAPQ and the SA tag.
  • Internal gap read as a clip: a large D near the end versus an S. Read the CIGAR op: D consumes reference, S does not.
  • Strand error: FLAG 0x10 set when the read should be forward. Check the flag, not the sequence.
  • Cross-tool convention mismatch: SAM POS is 1-based, PAF is 0-based. Round-trip a known alignment through both and compare.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Align chromosome-scale sequences under memory constraints.

Answer

Assumptions first. Two chromosome-scale sequences, say 250 Mb each (human chr1 is 249 Mb). Before choosing anything I need three facts: expected divergence (same species, or cross-species?), whether the alignment must be provably optimal or just good, and the memory budget. Those three decide the method; the sequence length only tells me full DP is off the table.

The core answer. Full Needleman–Wunsch is dead on arrival. The matrix is (m+1)(n+1) = 6.25e16 cells. At 1 byte per cell that is 62 PB; at 4 bytes, 250 PB. Even with infinite memory, 6.25e16 cell updates at a generous 1e9/s is about two years. So the answer is never "run full DP": it is "pick the structure that avoids materializing the matrix." There are three levers, and at chromosome scale you combine them.

1. Linear space (Hirschberg). The score of the best alignment ending at (i, j) depends only on row i-1 and row i, so you can sweep rows keeping two rows and still get the final score. Hirschberg recovers the path by splitting the second sequence at its midpoint, finding the row where the forward and backward score vectors sum to the optimum, and recursing on the two halves. Memory drops to O(min(m,n)), two rows of 250 Mb at 4 bytes is ~2 GB, but time stays O(mn), so this fixes memory, not time. Use it when you need a guaranteed-optimal global alignment and can wait, e.g. validating a heuristic on a small region.

2. Banding. If the sequences are near-identical the optimal path stays within k of the diagonal, so time and space fall to O(mk). At 1% divergence you need k ≈ 2·0.01·250e6 = 5 Mb, giving ~20 MB of memory, but 250e6 × 5e6 = 1.25e15 updates, roughly 14 days at 1e9/s. Banding alone is not enough at chromosome scale.

3. Seeding. Extract exact-match anchors (minimizers, or maximal exact matches), chain them into a collinear skeleton, then run banded DP only inside each chain. minimap2's asm20 preset (tuned for up to ~20% divergence) and MUMmer4 (MEMs via suffix array) do exactly this. Anchors are O(n/w), so chaining is near-linear and base-level DP touches only chain interiors.

Trade-offs.

approachtimespaceoptimal?when to use
full DPO(mn)O(mn)yessmall sequences only
HirschbergO(mn)O(min(m,n))yesneed optimal, can wait
bandedO(mk)O(k)only if path stays in band<1% divergence
seeded + banded~O(n + a log a)O(anchors)heuristicchromosome scale, divergent

Failure modes and how to detect them.

  • Out of memory: watch RSS. If it climbs past budget you are still materializing the matrix: switch to Hirschberg or seeding.
  • Band excludes the optimum: the score plateaus or identity drops at the band edge. Widen k and re-run; if the score improves, the band was too narrow.
  • Coordinate overflow: 250e6 × 250e6 = 6.25e16 overflows int32 (max 2.1e9). Use int64 for cell counts and offsets; detect by negative or wrapped indices.
  • Hidden traceback storage: a "linear-space" library that still allocates the full traceback matrix. Check peak RSS, not the API name.
  • Pairwise DP for database search: O(mn) per pair across millions of pairs is hopeless; use an index (BWA, minimap2) instead.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Interpret a BLAST hit with E-value 1e-20.

Answer

The 60-second answer. An E-value of 1e-20 means that if you searched a database of this size with a random sequence of this length and composition, you would expect 1e-20 alignments to score this well or better by chance: roughly one in 10^20. So the alignment is not noise. What it does not say is that the two proteins do the same thing: the E-value measures score significance under a null model, not functional identity. My next move is to look at the alignment itself (percent identity, alignment length, query coverage) and then at domain and experimental evidence before transferring any annotation.

Where the number comes from. BLAST scores an alignment with a substitution matrix and gap penalties, converts the raw score S to a bit score S′ = (λS − ln K)/ln 2, then computes E = m·n·2^(−S′), where m is the query length and n is the total number of residues in the searched database. λ and K are the Karlin–Altschul parameters fixed by the matrix and gap costs; for BLOSUM62 with gap open 11 / extend 1 they are about λ = 0.267 and K = 0.041. Scores of random alignments follow an extreme-value (Gumbel) distribution, and E is the tail of that distribution scaled by the search space.

Sanity-check the number. Worked example with hypothetical figures: a 300-residue query against a 4×10^7-residue database gives m·n = 1.2×10^10. Setting E = 1e-20 gives 2^(−S′) = 8.3×10^-31, so S′ ≈ 100 bits. A 1e-20 hit here is therefore a roughly 100-bit alignment: a long, high-identity match, not a 20-residue fluke. The same alignment against a database ten times larger reports E ≈ 1e-19, and against nr, which is orders of magnitude larger still, the same bit score gives a correspondingly larger E. E scales linearly with database size; the bit score does not. That is why you report both.

What I check before believing it. Coverage and identity: 1e-20 over 250 of 300 residues at 40% identity is a solid homolog; 1e-20 over 25 residues of a proline-rich or coiled-coil region is a composition artefact. Low-complexity masking (SEG for protein, DUST for nucleotide) and composition-based statistics (BLAST+ default -comp_based_stats 2 for blastp) are on by default for a reason: turn them off and short biased matches inflate. Then domain evidence: does the hit carry a Pfam or CDD domain matching the query's expected architecture? Then experimental evidence: is there a characterised member of that family with a known function?

Failure modes and how I catch them. Treating E as a posterior probability of homology: catch it by asking what the null model is; a 1e-20 hit at 25% identity over 60 residues is still weak. Ignoring database size: catch it by recomputing E for the database you actually care about. Repetitive queries: catch it by looking at the HSP map; a query with tandem repeats produces many HSPs and an optimistic E. Contamination: catch it by BLASTing against UniVec or the host genome; if the top hits are all vector or all one organism, the query is contaminated. Multiple testing: screening 10^5 queries at E = 1e-5 expects one false positive, while at 1e-20 it expects 1e-15, so this hit survives, but a universal cutoff does not.

When sequence evidence is not enough. If the hit is long and high-identity against a characterised protein, transfer the annotation. If it is short, biased, or to an uncharacterised protein, sequence alone will not settle it: go to profile methods (HMMER, PSI-BLAST, MMseqs2), which are more sensitive for remote homology, and to structure or experiment. A BLAST E-value of 1e-3 that HMMER confirms at 1e-20 is real; a BLAST 1e-20 that HMMER does not reproduce is usually composition.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

Choose a BLAST program for finding unannotated coding loci.

Answer

The 90-second answer

Assume a eukaryotic genome with no usable annotation, a protein query from a related species, and "coding locus" meaning a protein-coding gene the annotation missed. The program is tblastn: protein query, nucleotide database translated in all six frames.

blastn is the reflex answer and the wrong one. It compares nucleotides directly, so it needs the query and the locus to still look alike at the DNA level. Coding sequence diverges fastest at the third codon position, where most substitutions are synonymous, and a genomic locus also carries introns that blastn cannot span at all. At 30% amino acid identity, the twilight zone where remote homologs live, the underlying codons are close to random and blastn sees nothing, while tblastn still scores a significant alignment because BLOSUM62 rewards conservative substitutions.

Mechanism and cost

tblastn translates the database in all six reading frames and runs a protein-protein alignment against each. Defaults in BLAST+ 2.16: -word_size 3, BLOSUM62, -gapopen 11 -gapextend 1, -evalue 10, SEG low-complexity filtering on for the protein query, -db_gencode 1. The word size of 3 versus blastn's 11 is what buys the sensitivity, and it is also why the search is slow.

The arithmetic: a 3.1 Gb mammalian genome becomes 6 × 3.1 = 18.6 Gb of translated residues searched per query. A blastp run against a 20,000-protein proteome (~400 aa each, ~8 Mb) searches roughly 2,300× less sequence. E-values are computed against that 6-frame search space, so they are already corrected for the inflation: set -evalue 1e-5 for a first pass and read them at face value.

tblastn -query query.faa -db genome -evalue 1e-5 -seg yes -db_gencode 1 \
        -outfmt "6 qseqid sseqid pident length evalue bitscore sframe" > hits.tsv

Choosing between the translated programs

ProgramQuery → SubjectUse it when
blastn / megablastDNA → DNAsame-species or near-identical homologs, cDNA/EST, no introns in the way
tblastnprotein → 6-frame DNAunannotated coding loci, cross-species protein conservation
blastx6-frame DNA → proteinyou have a transcript or contig and want to know what it encodes
tblastx6-frame DNA → 6-frame DNAneither side has protein; slowest, last resort

When tblastn is the wrong tool: if a closely related annotated genome exists, blastn or a synteny lift-over is cheaper and more precise. If protein identity is below ~25%, BLAST's local alignment runs out of signal: switch to profile HMMs (HMMER3 phmmer/jackhmmer) or structure search. If RNA-seq exists, align reads and call ORFs directly.

Failure modes and how you catch them

  • Intron-split HSPs. tblastn has no splice model, so a multi-exon gene returns fragments on the same frame and diagonal, each with a worse E-value. Detect by clustering HSPs separated by 50–10,000 bp gaps; fix with miniprot, Exonerate or GeneWise.
  • Frame artifacts and pseudogenes. Translate the hit region and look for internal stop codons or frameshifts. A hit with a frameshift is a pseudogene candidate, not a coding locus.
  • Genetic-code mismatch. -db_gencode 1 is wrong for mitochondrial or non-standard genomes; hits vanish or look scrambled. Set the code explicitly for organelle databases.
  • Low-complexity queries. Coiled-coil or proline-rich proteins return thousands of hits even with SEG on. If hit count is orders of magnitude above expectation and spread across many contigs, filter the query.
  • -max_target_seqs truncation. It keeps the first N hits in database order, not the best N. Leave it high or post-filter on bitscore.
  • Hit ≠ expressed gene. tblastn says nothing about transcription. Confirm with RNA-seq or EST coverage, an intact ORF, and canonical GT–AG splice sites before calling it a locus.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Walk me through the BLAST algorithm workflow: how are seed hits identified, extended into HSPs, and evaluated for statistical significance?

Answer

The 90-second answer. BLAST is a heuristic for Smith–Waterman local alignment: seed, extend, score. It finds short word matches between query and database, extends them along the diagonal into ungapped high-scoring segment pairs (HSPs), re-extends the survivors with gaps, then converts the raw score into a bit score and an E-value using Karlin–Altschul theory. Two choices buy the speed. Protein searches precompute a neighborhood of words for each query word, so one seed matches many database words at once. The two-hit heuristic only pays for an extension when two seeds land on the same diagonal close together. Extension is the expensive step, so skipping most of it is the whole game.

1. Seeding. For each query position BLAST takes the w-mer starting there. Defaults: w=3 for blastp, 11 for blastn, 28 for megablast. blastn requires exact word matches. blastp scores the query w-mer against all 20³ = 8000 words under BLOSUM62 and keeps every word scoring ≥ T (default T=11); at w=3, T=11 that is roughly 50 neighborhood words per query position. Lower T finds more distant homologs but inflates the lookup and the number of extensions.

Each database word matching a neighborhood word is a hit, and hits are grouped by diagonal: the offset between query and subject position. The two-hit heuristic (default for blastp, window 40 residues; blastn and megablast default to one-hit, window 0) requires two non-overlapping hits on the same diagonal within 40 residues before extension starts.

Trace, blastp, w=3, T=11. Query MKTAYIAKQR, subject MKTAYVAKQR (I→V at position 6). The query's 3-mers are MKT, KTA, TAY, AYI, YIA, IAK, AKQ, KQR; the subject's are the same except AYV, YVA, VAK where the substitution sits. The five exact matches (MKT, KTA, TAY, AKQ, KQR) all land on diagonal 0, so the two-hit rule fires on the first pair and extension runs. The three words spanning the substitution never seed, but extension recovers the region between the seeds.

2. Extension into HSPs. Ungapped extension walks both directions along the diagonal, adding substitution scores and tracking the peak S_max; it stops when the running score drops X below the peak (default X=20 for blastp). In the trace the aligned pairs score M-M 5, K-K 5, T-T 5, A-A 4, Y-Y 7, I-V 3, A-A 4, K-K 5, Q-Q 5, R-R 5: an HSP of 48. If the HSP clears an intermediate cutoff, BLAST runs a banded gapped extension with affine gap penalties (default 11/1 for BLOSUM62), again stopping when the score falls below the peak by the gapped dropoff (default 30). Banding keeps the DP near the seed diagonal instead of filling the full m×n matrix.

3. Karlin–Altschul statistics. Raw score S depends on the matrix and gap costs, so it is not comparable across searches. BLAST converts it to a bit score and then an E-value:

S' = (λS − ln K)/ln 2, E = m'n' · 2^(−S')

λ is the positive root of Σ p_i p_j e^(λ s_ij) = 1; K is a scale constant. m' and n' are effective lengths, m' = m − l and n' = n − N·l (N is the number of database sequences), where l = ln(Kmn)/H is the expected HSP length and H is the matrix's relative entropy. The correction matters because an HSP cannot start within l of a sequence end.

Worked arithmetic: BLOSUM62 with gap costs 11/1 gives λ = 0.267, K = 0.041, H = 0.14. A raw score S = 100 gives λS = 26.7 and ln K = −3.19, so S' = (26.7 + 3.19)/0.693 = 43.1 bits. Against a 300-residue query and a 10⁷-residue database, l = ln(0.041 × 300 × 10⁷)/0.14 ≈ 133, so m' ≈ 167 and n' ≈ 10⁷, giving m'n' ≈ 1.7×10⁹. Then 2^(−43.1) ≈ 1.0×10⁻¹³ and E ≈ 1.8×10⁻⁴: significant at the usual E ≤ 0.05 threshold. E scales roughly linearly with database size (a 10× larger database gives E ≈ 1.6×10⁻³); the bit score does not change.

KnobDefaultEffect
word size w3 (blastp), 11 (blastn), 28 (megablast)smaller → more seeds, more sensitive, slower
neighborhood threshold T11 (blastp, BLOSUM62)lower → more neighborhood words per seed
two-hit window40 residues (protein)larger → more extensions triggered
ungapped dropoff X20 (blastp)larger → longer ungapped HSPs
E-value cutoff10reporting threshold, not a significance test

Failure modes and how you'd catch them.

  • Low-complexity or repeat regions seed and extend to high scores, producing spuriously low E-values. BLAST masks them by default (SEG for protein, DUST for nucleotide); with masking off, look for a single repeated residue or a repeat family in the alignment.
  • Compositional bias inflates protein scores. BLAST+ applies composition-based statistics by default for blastp; disabling it inflates scores on skewed sequences.
  • The two-hit heuristic never extends a true homolog that produces only one strong seed on the diagonal. Lower T or w to recover it, at the cost of runtime.
  • Karlin–Altschul assumes long sequences; E-values for very short queries are unreliable: treat them as a ranking, not a probability.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How does BLAST's two-hit heuristic decide when to trigger an extension, and why does it outperform single-hit extension in throughput without losing sensitivity?

Answer

The short answer

BLAST seeds by finding short word matches between the query and each database sequence. The 1990 program extended every seed whose score met the threshold $T$. Gapped BLAST (Altschul et al., 1997) extends only when two non-overlapping seeds land on the same diagonal within a window $A$.

For query position $q$ and subject position $s$, the diagonal is $d = q - s$. BLAST keeps, per diagonal, the position of the most recent hit. A new hit on diagonal $d$ triggers an extension only if the previous hit on $d$ is within $A$ residues and does not overlap it. The extension starts at the second hit, runs backward through the first, and continues forward. If the ungapped alignment's score exceeds $S_g$, a gapped alignment is computed.

The rule is a filter on seeds, not on scores. Random hits are sparse and roughly independent, so a random hit is rarely followed by another within $A$; a true homolog produces many hits along one diagonal, so it almost always satisfies the rule. That asymmetry is the whole trick: it removes most doomed extensions while barely touching real ones, and the budget saved is spent lowering $T$, which recovers sensitivity for divergent homologs.

Mechanism details

  • Diagonal: $d = q - s$. Two hits share a diagonal iff $q_1 - s_1 = q_2 - s_2$.
  • Window: $A = 40$ residues in the 1997 protein implementation. The two hits must be non-overlapping.
  • The ungapped extension uses the X-dropoff criterion introduced in the same paper: extend while the running score stays within $X$ of its maximum, stop when it falls $X$ below. Each extension is therefore cheap and bounded.
  • Gapped extension fires only if the ungapped HSP score exceeds $S_g$.

Why throughput improves: the arithmetic

Take BLOSUM62, $W = 3$, $T = 11$ (the current BLAST+ blastp defaults). Roughly 50 of the 8000 possible 3-mers score $\ge 11$, so the per-position hit probability is $p \approx 50/8000 \approx 0.006$.

  • One-hit: an extension fires at every hit, rate $p$ per diagonal position.
  • Two-hit: an extension fires only when a previous hit lies within $A = 40$, rate $p,(1-(1-p)^{40}) \approx p^2 A \approx 1.4 \times 10^{-3}$.

Ratio $\approx pA \approx 0.25$: roughly 4× fewer extensions for these parameters. The factor is $pA$, so it grows as hits get rarer (higher $T$, less biased composition) and shrinks as they get denser. Seed lookup is a table/hash probe, $O(1)$ per position, so the extra bookkeeping is negligible next to the extensions removed.

Why sensitivity survives

The filter discriminates on a feature that correlates with homology, clustering of hits along one diagonal, rather than on score alone. A true HSP of length $\ge 40$ typically contains several qualifying words, so the chance it produces only one hit inside a 40-residue window is small. Because the filter is that selective, the threshold can be lowered ($W = 3$, $T = 11$ instead of a larger word size with a higher threshold), which seeds more divergent homologs. Net effect: comparable or better sensitivity at a fraction of the extension cost.

Failure modes

  • Short homologs. A conserved motif shorter than about $A$ that yields a single qualifying word is never extended. Mitigation: lower -word_size (e.g. 2) and -threshold, which raises seed density at the cost of many more extensions, or use a tool built for short matches.
  • Indels splitting the seed pair. A single indel shifts the diagonal, so two hits straddling it land on different diagonals and never trigger. If the conserved stretch on either side is shorter than $A$, the alignment is missed.
  • Low-complexity and repetitive sequence. These produce dense hits on many diagonals, so the two-hit rule fires constantly and stops filtering; throughput degrades. BLAST masks them by default (SEG for proteins, DUST for nucleotides), which is what keeps hits sparse enough for the heuristic to pay off.

Detection: run a known distant homolog as a positive control; if it is missed, compare against a more sensitive search (PSI-BLAST, HMMER) on the same query.

Comparison

One-hit (1990)Two-hit (1997 / BLAST+)
Triggerevery word hit scoring $\ge T$two non-overlapping hits on the same diagonal within $A$
Protein seedinglarger word size, higher $T$$W = 3$, $T = 11$ (BLOSUM62)
Extensionsone per hitone per qualifying hit pair
Dominant costungapped extensionseed lookup + extension

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

How do Karlin-Altschul statistics derive bit scores and E-values from raw local alignment scores, and when does the underlying model break down?

Answer

The 90-second version

Raw alignment scores are in arbitrary units: double every entry in the substitution matrix and every score doubles, but nothing about the biology changed. Karlin-Altschul turns that arbitrary number into a probability.

Assumptions I'd state up front: the two sequences are random and independent, residues are drawn i.i.d. from the background frequencies the matrix was built for, we're looking at local alignments, and, load-bearing, the expected score of a random residue pair is negative. Under those, the maximum local alignment score follows a Gumbel extreme-value distribution, not a normal one:

P(S ≥ x) ≈ 1 − exp(−K·m·n·e^(−λx)), so E = K·m·n·e^(−λS).

m·n is the search space, λ rescales the arbitrary score units, K absorbs the search-space geometry. λ isn't fitted: it's the unique positive root of Σ p_i q_j e^(λ s_ij) = 1: the exponential tilt under which the random walk of partial scores has zero drift. No positive root means the expected score isn't negative and the model is off.

Bit scores are a change of units: S' = (λS − ln K)/ln 2, chosen so E = m·n·2^(−S'). One extra bit halves the E-value; doubling the database doubles it.

Working it through

Python
import math

# toy 2-letter matrix, uniform background
p = [0.5, 0.5]
s = [[1, -2],
     [-2, 1]]

def char_eq(lam):
    return sum(p[i]*p[j]*math.exp(lam*s[i][j])
               for i in range(2) for j in range(2)) - 1.0

lo, hi = 0.0, 5.0
for _ in range(60):
    mid = (lo + hi) / 2
    if char_eq(mid) > 0: hi = mid
    else: lo = mid
lam = (lo + hi) / 2          # 0.4813

# raw score -> bit score -> E-value (BLOSUM62 ungapped)
lam62, K62 = 0.318, 0.13
m, n, S = 250, 10**8, 100
S_bit = (lam62*S - math.log(K62)) / math.log(2)   # 48.82
E = m * n * 2**(-S_bit)                            # 5.03e-05

char_eq(λ) = 0.5e^λ + 0.5e^(−2λ) − 1. It's 0 at λ=0, dips to a minimum of −0.055 at λ=0.231, then crosses zero once more at λ* = 0.4813: the positive root. Bisection on [0, 5]:

iterlohimidchar_eq(mid)
00.00005.00002.5000+5.095
10.00002.50001.2500+0.786
20.00001.25000.6250+0.077
30.00000.62500.3125−0.049
40.31250.62500.4688−0.005
50.46880.62500.5469+0.031
…0.48130

Then the conversion with BLOSUM62 ungapped λ=0.318, K=0.13, raw score S=100: S' = (0.318·100 + 2.040)/0.6931 = 48.82 bits. Against m=250, n=10^8: E = 2.5×10^10 × 2^(−48.82) = 5.0×10^(−5). The P-value 1 − e^(−E) equals E to five decimals at that magnitude.

Where it gets real

Gapped alignments have no closed-form λ and K; BLAST estimates them by simulating random alignments, which is why they're tabulated per matrix and gap scheme. BLOSUM62 ungapped: λ ≈ 0.318, K ≈ 0.13, H ≈ 0.40. Add an 11/1 gap cost and λ drops to 0.267, K to 0.041, H to 0.14. H is relative entropy per residue, and it matters because BLAST uses effective lengths m', n': subtracting an edge correction that grows like ln(K·m·n) and shrinks as H grows, since hits can't start at the very end and still extend.

When the model breaks

  1. Expected score not negative. If gap costs are too cheap relative to substitution scores, Σ p_i q_j s_ij ≥ 0, the characteristic equation has no positive root, and BLAST can't compute λ. Scores then grow linearly with alignment length instead of staying in the Gumbel regime. Tell: longer alignments keep scoring higher without bound.

  2. Compositional skew. λ and K assume the matrix's background frequencies. Transmembrane helices, coiled-coils, low-complexity runs and AT/GC-biased genomes violate independence. Detection: hits made almost entirely of one or two residue types with tiny E-values on sequence nobody would call homologous. Fix: composition-based statistics (-comp_based_stats), on by default for protein searches in BLAST+.

  3. Short sequences. The edge correction can exceed the sequence length, so m' goes non-positive and the E-value is meaningless. Detection: queries under roughly 20 residues. Fix: -task blastp-short or exact statistics.

  4. Database redundancy. Duplicated proteins or near-identical viral strains inflate n without adding independent search space, so genuine hits get E-values that are too large. Detection: many hits at 100% identity to each other.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Rank and filter BLAST alignments.

Answer

Core answer (first 90 seconds)

Pin down three things before you filter anything: what the search is for (ortholog assignment, domain annotation, or just "is there any homolog"), which program (blastn and blastp have different defaults and different identity regimes), and which database. The ranking rule changes with all three.

Then: rank by bit score, not raw score and not percent identity. Bit score is the raw score normalized by the scoring system's Karlin–Altschul parameters, S′ = (λS − ln K)/ln 2, so it is comparable across hits within one matrix and gap scheme and independent of database size. Use E-value as the first filter, not the ranker, because E = m·n·2^(−S′) scales linearly with database size n: the same hit scores 100× worse against a database 100× larger.

Concretely: BLAST+ defaults to -evalue 10 and -max_target_seqs 500. A working protein filter is E < 1e-5, query coverage ≥ 70%, identity ≥ 30% (the twilight zone below which homology calls are unreliable). For blastn at species level, identity ≥ 95% and coverage ≥ 90%.

Worked example (hypothetical, blastp, 400 aa query, 10^7-residue custom DB):

hitaligned lenidentitybit scoreE-valuecoverage
A30045%2501e-7075%
B6095%901e-2015%

Rank by identity → B wins. Rank by bit score → A wins, and A is the right call: B is a short conserved domain, not a homolog of the whole protein. Coverage is what catches it.

Failure modes and how you detect them

  • Fragmented HSP inflation: one subject reported as three HSPs on the same frame with adjacent query coordinates. Summing their bit scores overstates support. Detect by grouping HSPs per subject and using the best HSP, or summing only non-overlapping ones.
  • Short-domain dominance: coverage column below your threshold while the E-value looks strong. Detect by filtering on coverage before you look at rank.
  • Paralog selection: the top five hits sit within 1–2% identity of each other, so the "best" hit is arbitrary. Detect with reciprocal best hits against the query's own proteome.
  • Database bias: E-values from a small custom DB and from nr are not comparable. Detect by comparing n; if it differs, re-rank on bit score.
  • Lost ties: hit 500 and hit 501 have identical bit scores and max_target_seqs truncated between them. Detect by checking the score at the cutoff.

Trade-offs

If the only question is "is there any homolog", same program, same database, no ortholog claim downstream, a plain E < 1e-5 cutoff is fine and multi-criteria filtering just adds false negatives. Multi-criteria earns its keep when you are assigning orthologs, comparing across databases, or annotating domains: there, coverage and reciprocal best hits decide, and E-value alone will pick paralogs and fragments.

What would change the decision

If the goal is domain annotation rather than whole-protein homology, BLAST is the wrong tool: profile HMMs (Pfam/HMMER) score domains directly and do not have the HSP-fragmentation problem. If you must compare hits across databases, drop E-value from the ranking entirely and use bit score plus coverage.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Combine multiple HSPs for candidate review.

Answer

Core answer (first 90 seconds). Don't merge by default. BLAST already does the merge you'd want: for each database sequence it sums the scores of HSPs that lie on the same strand and don't overlap, and that summed score is what the reported E-value comes from (Altschul et al., Nucleic Acids Research 1997). So the real question isn't "how do I add HSPs up": it's "is this HSP set one alignment or several?" I check four things in order: same strand, collinear order on both query and subject, consistent reading frame, and no overlap. If all four hold and the gaps between HSPs look like introns or a short indel, I report the combined alignment and its E-value. If any fails, I keep the best HSP as the alignment and treat the rest as separate evidence.

Why summing is dangerous. Karlin–Altschul gives E = K·m·n·e^(−λS), so each extra bit halves the E-value. Two 50-bit HSPs summed to 100 bits drop E by 2^50 ≈ 1.1×10^15. That is exactly why people want to merge: a genuinely fragmented homolog looks insignificant HSP by HSP, and BLAST's default reporting threshold is E ≤ 10. It is also why a naive sum overstates: if those two HSPs overlap by 30 residues, BLAST's rule excludes the overlap, but a script that adds every HSP's bitscore does not.

Alternatives, and when each is right.

approachwhat it computesuse whenfails when
single best HSPhighest-scoring HSP onlyone clean domain; paralog soupa real multi-domain hit looks weak
BLAST sum-of-HSPssum of same-strand, non-overlapping HSPscollinear fragments of one homologrepeats, chimeras, opposite strands
chained / gapped (miniprot, Exonerate, MMseqs2, DIAMOND)explicit chain with gap costs, splice-awareprotein-to-genome, long indels, intronsno intron model → over-gapping
full Smith–Watermanoptimal local alignmentshort queries, validationO(mn), too slow at scale

Failure modes and how I catch them.

  • Double-counted overlap. Sort HSPs by subject start, test interval intersection; compare your total to BLAST's reported bitscore. A mismatch means you summed something BLAST deliberately didn't.
  • Opposite strand / reversed order. Sign of sstart vs send; check collinearity on both axes, not just one.
  • Mixed frames. frame = (qstart − 1) mod 3. Two frames on one query is a frameshift or pseudogene, not a merge candidate.
  • Repeat fragments. Many short HSPs to low-complexity sequence: high HSP count, low coverage. Mask with dustmasker or RepeatMasker and re-run.
  • Chimeric record. Subject span ≫ sum of HSP lengths, or HSPs landing on different contigs.
  • One-domain annotation transfer. coverage = aligned query length / query length; below roughly 70% I don't transfer a full-length annotation.
  • Parser truncation. BLAST outfmt 6 default is 12 columns (qseqid sseqid pident length mismatch gapopen qstart qend sstart send evalue bitscore); parse fewer and you lose gaps and frame. Assert the column count.

When not to combine. Paralogs and repeat families: two HSPs from different copies can look collinear but are not one alignment. Same for different strands or frames: that's a pseudogene or a misassembly, and merging hides it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Choose BLAST sensitivity settings.

Answer

Core answer. Before touching a flag, pin three things: what the query is (nucleotide or protein, and how long), what the database is (size, version, genome or domain collection), and what "sensitive" means here. Finding close orthologs, or pushing into remote homology. Those decide the task preset, and the preset decides most of the defaults. Then I set word size and matrix, leave the E-value at 10 for the initial scan, and validate on a labelled positive set plus decoys before trusting any number.

Mechanism. BLAST is seed-and-extend. It finds exact words of length w in the query, requires two non-overlapping hits on the same diagonal within a window (default 40 for blastp) before it bothers extending, extends ungapped while the score rises, then runs a gapped extension that stops when the score drops past the X-drop threshold. Only then does it compute a bit score and an E-value. Every knob moves one of those stages:

  • Word size sets the seed. Smaller means more seeds, more sensitivity, quadratically more work. blastp defaults to 3; dropping to 2 finds more distant homologs at roughly an order of magnitude more time. blastn megablast defaults to 11, which is why a 20 nt primer barely seeds: the blastn task drops to 7.
  • Matrix sets what counts as a good substitution. BLOSUM62 (blastp default) is tuned around 62% identity; BLOSUM45 or BLOSUM80 shift the detectable range down or up. Matrix and gap costs are coupled: changing one alone usually just moves the noise floor.
  • Thresholds. E-value 10 is the default and is a reporting threshold, not a significance one. Bit score is database-size independent; E-value is not.

E-value arithmetic. E ≈ K·m·n·e^(−λS). Same hit, same score, database grows 1000× (10^6 → 10^9 residues): E grows 1000×. A hit at E = 1e-5 in the small database is E ≈ 1e-2 in the large one. Thresholds must be re-derived whenever the database changes, and the database version recorded with the result.

Knobblastp defaultMore sensitiveFaster
word_size326
matrix (gap open/extend)BLOSUM62 (11/1)BLOSUM45 (14/2)BLOSUM80 (10/1)
two-hit window400 (off)larger
E-value10report 10, filter 1e-51e-5

Failure modes and how I catch them.

  • Missed remote homology: benchmark recall on a held-out set of known homolog pairs at a fixed false-positive rate; if recall falls short, lower word size or move to PSI-BLAST/HMMER.
  • Excess false hits: search a reversed (decoy) database; the count of decoy hits passing threshold estimates the FDR directly.
  • Short queries: if a 25 nt query returns nothing, rerun with -task blastn-short (word size 7) and compare. Hits that appear only then mean the seed length was the problem.
  • Low-complexity masking: rerun with -seg no / -dust no; hits that exist only unmasked are composition artefacts.
  • Wrong preset: run megablast and dc-megablast on the same query; cross-species hits that appear only in dc-megablast tell you the preset was wrong.
  • Database drift: record database name, version and date; re-run a fixed positive set after each update and diff the E-values.

When BLAST is the wrong tool. Below roughly 25–30% identity, substitution-matrix scoring runs out of signal. Profile methods (PSI-BLAST, HMMER) or structure search (Foldseek) are the right call; BLAST returning nothing there is not evidence of no homology.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Choose masking policy for a repeat-rich protein family.

Answer

Assumptions. "Repeat-rich" here means the family's real members carry long low-complexity or tandem-repeat stretches (proline-rich, coiled-coil, poly-Q, zinc-finger arrays) not that the repeat is the domain (as in ankyrin). The job is a homology search: BLASTP against nr, or HMMER against a proteome, to find and annotate new members.

The policy: soft masking, not hard. Mask the query with SEG at its defaults (window 12, locut 2.2, hicut 2.5), keep the masked residues in lowercase, and run BLAST+ with -soft_masking true set explicitly rather than trusting the default. Keep the unmasked sequence as the reference for reporting and for the alignment you show. Then confirm every candidate with a family HMM built from a curated alignment (hmmbuild, default --symfrac 0.5) and hmmsearch, and check the hit's domain architecture.

blastp -query family.faa -db nr -seg yes -soft_masking true \
       -comp_based_stats 2 -outfmt "6 qseqid sseqid evalue bitscore qstart qend"
hmmbuild family.hmm family.sto
hmmsearch --domE 1e-5 family.hmm proteome.faa

Why soft and not hard. A low-complexity region has a skewed composition, so it produces few distinct k-mers and each occurs many times. BLAST's word lookup finds those words in unrelated proteins by chance, so a query full of them seeds everywhere; the chance seeds extend into short high-scoring alignments that inflate the hit list and push real hits down the ranking. SEG marks the windows whose composition deviates from background (2.2 and 2.5 are the low and high entropy cutoffs). Soft masking drops those positions from the lookup table only: the extension step still scores them, so a homolog that shares the repeat still earns bits. Hard masking replaces them with X, which the extension also refuses to score, so a homolog whose only shared region is the repeat collapses to near zero and vanishes.

policyeffect on seedingeffect on alignment scorechoose when
no maskingevery low-complexity word seedsfullshort query, few repeats, you will curate by hand
soft masking (SEG, lowercase)biased words removedfulldefault for a repeat-rich family
hard masking (SEG → X)biased words removedrepeat region scores zeroyou only care about non-repeat domains
family HMM, no maskingemission probabilities down-weight biased columnsfullthe family is defined and you have a curated alignment

Failure modes and how to catch them.

  • Masked true motif. A short functional motif (a binding site, an NLS) falls inside a SEG window. Re-run with -seg no and diff the hit lists; anything present only unmasked is a candidate to inspect by hand.
  • Unmasked spurious hit. A biased hit survives because masking was off or the region sat below the cutoff. Check the aligned region's composition against a background, and see whether the hit disappears under -comp_based_stats 2.
  • Asymmetric masking. Query masked, database not, or the reverse. Log the exact command line for both sides together; they must be recorded as a pair.
  • Coordinate drift. Hard masking plus trimming renumbers the query, so a reported motif position no longer matches the reference. Keep the unmasked sequence as the coordinate reference and never renumber.
  • Undocumented default. BLAST+ applies SEG to blastp by default, so a search you believed was unmasked was masked. Print the resolved -seg and -soft_masking values into the run log.

For a defined family, the HMM row is usually the better answer than any masking: the model's per-column emissions already discount the biased positions, so you get the specificity without throwing away the repeat's contribution to a true match.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Compare results from custom and comprehensive databases.

Answer

What actually differs. The alignment itself (bit score, percent identity, alignment length) is a property of the query and the subject sequence, not the database. The same HSP scores the same in both runs. Two things change: the E-value and the composition of the hit list.

E-value is where the database enters. For bit scores the relation is exact:

E = m · n · 2^(−S)

m is query length, n is the total residues searched, S is the bit score. Same HSP → same S → E scales linearly with n.

Worked example. 300 aa query, BLOSUM62. Custom database of 10^7 residues; nr at 10^11 residues: a 10^4× search-space ratio.

databasen (residues)E at S = 60
custom10^72.6 × 10^−9
nr10^112.6 × 10^−5

Check: m·n = 300 × 10^7 = 3 × 10^9; 2^−60 = 8.67 × 10^−19; product = 2.6 × 10^−9. For nr, m·n = 3 × 10^13, giving 2.6 × 10^−5.

Same alignment, four orders of magnitude apart. A hit scoring 44 bits gives E ≈ 1.7 × 10^−4 in the custom database and E ≈ 1.7 in nr: reported in one run, discarded in the other. A threshold copied from one run is meaningless in the other.

Second difference: hit-list composition. A larger database contains more chance matches (E in the 1–10 range) and more distant homologs. nr can surface a remote relative your custom set never contained, while burying a clade-specific hit under noise. Record the residue count and release string for each database, blastdbcmd -info prints both, and interpret E-values inside the run that produced them.

When custom is the right call. A narrow target (one genus, one protein family, a fixed set of assemblies); sensitivity to distant homologs inside a clade where nr's noise buries them; reproducibility, because a frozen release does not move under you; and cost: DIAMOND or MMseqs2 against 10^7 residues returns in seconds where nr takes minutes. Use nr or UniRef when the query is unknown, when you want broad discovery, or when the result has to be comparable to published work. UniRef50 clusters at 50% identity, shrinking n and lowering E-values, at the cost of strain-level resolution.

Failure modes and how you catch them.

  • Database-size confounding: E-values compared across databases without normalizing. Detect by rescaling E by the n ratio, or by re-searching both hit sets against one common database.
  • Duplicate records: inflate n and therefore inflate E-values. Detect by comparing unique accessions against total entries in blastdbcmd -info.
  • Taxonomy skew: a hit list dominated by one organism. Detect with a taxid histogram over the top 100 hits; if one genus is most of them, the database is not representative.
  • Obsolete build: detect by recording the release string and date and re-running against the current release.
  • Contaminated custom database: vector, primer or adaptor sequence. Detect by screening the database against UniVec and inspecting top hits.
  • Incomparable parameters: matrix, gap penalties, word size, -max_target_seqs, -comp_based_stats. Detect by diffing the two command lines. Composition-based statistics (default 2 for blastp) can shift bit scores slightly when database composition differs, so "same bit score" holds only when that setting matches too.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Create an alignment input validator.

Answer

Assumptions first, because the question can't be answered without them. FASTA encodes no molecule type: the header is free text and the body is bare letters. So a validator is only meaningful once the caller declares (a) nucleotide or protein, (b) for nucleotide, whether the input is codon-aligned and which NCBI translation table applies, and (c) whether duplicate IDs are legal. I'll assume a pre-alignment gate for MAFFT/MUSCLE/IQ-TREE-class tools, nucleotide, table 1, duplicates illegal. Every choice below flips if those change.

Design. Stream the file, never materialise a record, and emit structured errors (code, record_id, line) rather than raising on the first one: the caller wants the whole defect list from one pass. Per record: header token, alphabet, length, and for coding input, frame and stop codons.

Python
# Python 3.11
NUC = set("ACGTUNRYSWKMBDHV-.")
PRO = set("ACDEFGHIKLMNPQRSTVWYBXZJUO*-")

def validate(path, molecule, max_record_bytes=1 << 30):
    seen, rid, n = {}, None, 0
    with open(path, "rb") as fh:
        for lineno, raw in enumerate(fh, 1):
            line = raw.rstrip(b"\r\n")
            if not line:
                continue
            if line.startswith(b">"):
                if rid is not None and n == 0:
                    yield "empty_record", rid, lineno
                parts = line[1:].split(None, 1)
                rid = parts[0].decode("ascii", "replace") if parts else ""
                if not rid:
                    yield "missing_id", None, lineno
                elif rid in seen:
                    yield "duplicate_id", rid, lineno
                seen[rid] = lineno
                n = 0
                continue
            if rid is None:
                yield "sequence_before_header", None, lineno
                continue
            n += len(line)
            if n > max_record_bytes:
                yield "record_too_large", rid, lineno
            alphabet = NUC if molecule == "nucl" else PRO
            bad = set(line.decode("ascii", "replace").upper()) - alphabet
            if bad:
                yield "bad_residue", rid, sorted(bad)
    if rid is not None and n == 0:
        yield "empty_record", rid, None

Trace on >seq1 first / ACGT / >seq1 second / ACGTN / >seq2:

  • L1 >seq1 first → rid seq1, seen={seq1:1}, n=0.
  • L2 ACGT → n=4; set("ACGT") - NUC is empty, no yield.
  • L3 >seq1 second → n=4 so not empty; seq1 already in seen → duplicate_id seq1 3; n reset to 0.
  • L4 ACGTN → n=5; N is in NUC, clean.
  • L5 >seq2 → n=5, not empty; seq2 recorded, n=0.
  • EOF → rid seq2, n=0 → empty_record seq2 None.

Two errors, one pass, no record held.

failuredetectioncost if missed
duplicate IDtoken before first whitespace already in seenindex-based lookups (samtools faidx, Bio.SeqIO.index) key on that token, so two records are indistinguishable to the index and alignment rows can't be mapped back
protein under nucleotide scorerresidue set: E, F, I, L, P, Q are not IUPAC nucleotide codes, so any real-length protein trips ita DNA model scores the protein as ambiguity codes; output looks plausible and is noise
whitespace truncationfull header vs token; >geneA and >geneA isoform2 collidetwo genes silently become one
reverse-complement omissionno strand field and no documented conventioncoordinates land on the wrong strand; ORF finder returns nothing
hidden stoptranslate in the declared frame, scan for *frameshift or wrong frame; a mid-protein stop. Table 4 (mold/protozoan) reads TGA as Trp, so the wrong table flags every TGA
unbounded inputbyte counter per record and totala 3.1 Gbp genome read as one string OOMs the worker

Strict vs lenient is the real decision. Strict-fail is right when output feeds a database or a regulated pipeline: a wrong alignment is worse than no alignment. It is wrong for draft assemblies and multi-contig files, where duplicate tokens are expected, and for soft-masked input: lowercase from RepeatMasker/dust is meaningful, so uppercasing destroys the mask. There, normalise case but record the mask flag, and downgrade duplicates to warnings. If the aligner validates on its own, skip the duplicate check.

What would change my answer: a one-off exploratory alignment tolerates lenient-with-warnings; anything persisted or clinical needs strict-fail, and a declared genetic code other than table 1 changes the stop-codon check entirely.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Build a robust BLAST result parser.

Answer

Core answer. Assume BLAST+ 2.x (the -outfmt field list is stable across 2.13–2.16). Decide the format before writing any parser: for automation use -outfmt 6 with an explicit field list, never the default 12-column order and never the human-readable -outfmt 0. Pin the BLAST version, capture stdout, stderr and exit code separately, validate every line, and treat "no hits" and "run failed" as different outcomes. Everything below follows from those four decisions.

Format choice.

-outfmtshapeuse when
6tab-separated, one line per HSP, no headerpipeline parsing; you must record the field list yourself
7same columns plus # comment lines (version, query, field names)you need to tell no-hit from crash: the header is emitted even with zero hits
5XML, self-describing, embeds search parametersyou need the parameters/statistics in the artefact
11ASN.1 archive, losslessyou must re-render later with blast_formatter

Tabular wins on cost and determinism; XML wins when the search parameters must travel with the hits; the archive wins when you cannot re-run the search. Pick one and record it.

Parser (Python 3.11):

Python
import subprocess

FIELDS = ["qseqid", "sseqid", "pident", "length", "evalue", "bitscore"]
OUTFMT = "6 " + " ".join(FIELDS)

def run_blast(query, db):
    cmd = ["blastn", "-query", query, "-db", db,
           "-outfmt", OUTFMT, "-max_target_seqs", "500"]
    p = subprocess.run(cmd, capture_output=True, text=True)
    if p.returncode != 0:
        raise RuntimeError(f"blastn exit {p.returncode}: {p.stderr[-500:]}")
    return p.stdout

def parse(text):
    hits = []
    for i, line in enumerate(text.splitlines(), 1):
        if not line.strip():
            continue
        cols = line.split("\t")
        if len(cols) != len(FIELDS):
            raise ValueError(f"line {i}: {len(cols)} cols, want {len(FIELDS)}")
        rec = dict(zip(FIELDS, cols))
        rec["pident"] = float(rec["pident"])
        rec["length"] = int(rec["length"])
        rec["evalue"] = float(rec["evalue"])
        hits.append(rec)
    return hits

Trace. The line q1\tsubjA\t99.5\t250\t1e-45\t480 splits into 6 fields, matches FIELDS, and yields pident=99.5, length=250, evalue=1e-45. A line with 5 fields raises ValueError at that line number instead of silently shifting columns.

Failure modes, with detection.

failuredetectioncost if missed
column-order driftassert len(cols) == len(FIELDS); store the field list with the resultspident and evalue silently swap
delimiter inside an identifierfield-count mismatchevery downstream column misaligned
coordinate conventionsstart > send means minus strand; blastx query coords are amino-acid spacewrong genomic interval
E-value underflowvalue parses as 0.0ranked as a perfect hit, or a divide-by-zero
truncated processlast line has no trailing newline, or short field countpartial hit set read as complete
duplicate HSPsgroup by (qseqid, sseqid)inflated hit counts
lost stderrcapture_output=True, log stderr on any non-zero exitsilent failure
empty output read as no-hitcheck exit code; with -outfmt 7 a header is present even with zero hitsa crash recorded as "no hits"

Underflow, specifically. BLAST prints 0.0 when the computed E-value underflows double precision. That is not "perfect hit": it is "smaller than representable". Do not rank on it and do not divide by it; treat 0.0 as a sentinel and keep bitscore as the ranking key.

Regression tests. Keep one small query against a fixed database per BLAST version you support, assert the exact field list and a handful of known coordinates, and re-run on upgrade. That catches column drift and coordinate changes before they reach production.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Make a database search reproducible.

Answer

Say this first (60-120 seconds)

Reproducible means: same query, same database content, same taxonomy, same parameters produces the same hits and the same bitscores. The database name gives you none of that. nt is a label pointing at whatever volume is installed; NCBI re-releases it, and the taxonomy that backs -taxids is rebuilt on its own schedule. So the thing you pin is a content address plus a provenance record, not a name.

Assumptions worth stating: local BLAST+ so you control the volume; reproduction may happen months later, after upstream has moved; storage for a full archive may not be available. Freeze four things - program version, database volume, taxonomy files, search parameters - and store the record beside the results, not in someone's shell history. Then decide, per experiment, whether you archive the volume or keep a recipe that rebuilds it.

What the record holds

  • Program: blastn -version. A scoring or parsing change between releases can move an E-value.
  • Database content: blastdbcmd -info reports the database name, build date, sequence count and total letters. Sequence count catches truncation; the date catches a re-release under the same name.
  • Database bytes: checksum the volume files. -db nt does not resolve to one fixed path - BLASTDB decides which directory wins, and a stale local copy carrying the same title is a real trap.
  • Taxonomy: -taxids and -taxidlist depend on taxdb.btd and taxdb.bti, which are downloaded separately from the sequence volume. Checksum those too.
  • Query: SHA-256 of the FASTA, plus the accession with version if it came from a repository. A bare accession re-resolves to a newer version later.
  • Command: the whole line, including -outfmt, -evalue, -word_size, -max_target_seqs.

Artefact 1 - capture, bash 5, BLAST+ 2.16.0:

Shell
set -euo pipefail
blastn -version          > blast_version.txt
blastdbcmd -db nt -info  > db_info.txt   # name, date, seqs, letters
md5sum nt.* taxdb.*      > db.md5
sha256sum query.fa       > query.sha256
printf 'BLASTDB=%s\n' "${BLASTDB:-unset}" > blastdb_path.txt

The re-run gate is the same commands diffed against that record. Any difference aborts the run before it starts.

Artefact 2 - archive versus re-derive:

Archive the volumeFrozen recipe + accession list
upfrontcopy the whole builda text file
months laterbit-exact, works offlineexact only if upstream left every sequence alone
coststorage and transfer for the full volumecheap to keep, but a rebuild is a real search, hours of CPU
fails whenthe archive is incomplete or split across machinesa sequence was withdrawn or replaced, or the taxonomy was rebuilt

Deciding criterion: what a one-hit difference costs you. Clinical or regulatory work archives. Exploratory work keeps a recipe plus the full parameter record and accepts that a rebuild means "same accessions, possibly different bytes".

Artefact 3 - failure modes and how each one shows up:

failurewhat happensdetection
silent updatent re-released under the same label with different membership; hits appear or vanish-info date or sequence count differs from the record
withdrawn or replaced sequencethe accession still exists but the sequence changed, so the frozen list rebuilds differentlycompare accession versions, never bare accessions
taxonomy remaptaxids merge, split or get renamed when taxdb is rebuilt; a -taxids filter keeps running but selects a different setchecksum taxdb.btd/taxdb.bti, and expand the taxon to an explicit taxid list once at pin time, then store the list
corrupted or partial volumethe search fails outright or returns short-info reports a lower sequence count; checksum mismatch
alias mismatchnt is a local build on one host and the NCBI release on another; identical command, different resultsrecord the resolved path and the BLASTDB value, never just the name
database orderwith -max_target_seqs set, BLAST keeps the first N hits in volume order, not the N best, so rebuilding the volume reorders what survivesre-run with -max_target_seqs high enough to be non-binding and compare

That last row is the one people miss. A rebuild that preserves membership but changes layout can change your reported hits, so reproducibility here covers the volume as laid out on disk, not only the set of sequences inside it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Construct a pairwise-alignment regression suite.

Answer

Core answer

Assume a Gotoh-style affine aligner with a fixed scheme: match +1, mismatch −1, gap −1 for the hand cases. The suite pins three things: the reported score, the validity of the traceback, and the boundary conventions. It is not a re-test of the DP recurrence.

Start with a matrix small enough to compute by hand. Take s1 = "ACGT", s2 = "AGT":

–AGT
–0−1−2−3
A−110−1
C−200−1
G−3−110
T−4−202

H(4,3) = 2, reached only from the diagonal, so the optimum is unique: ACGT / A-GT = +1 −1 +1 +1 = 2. Assert the score is 2, and assert the returned alignment rescores to 2.

Now a tie. Take s1 = "AT", s2 = "TA":

–TA
–0−1−2
A−1−10
T−20−1

H(2,2) = −1, reachable from both H(1,2)−1 and H(2,1)−1. Two optima: AT- / -TA and -AT / TA-, both rescoring to −1. Assert the score is −1 and that whatever path comes back rescores to −1. Never assert a specific path string: that locks in one tie-break and then fails a correct implementation.

Now the boundary. With affine gaps the first row and column are not k·gap; they are gap_open + (k−1)·gap_extend. For gap_open = −11, gap_extend = −1, H(0,3) = −13, not −33 and not 0. A suite that only exercises interior cells never sees this, and a linear-penalty initialization passes every interior test.

Alternatives and when to use each

designcatchescostuse when
Hand-computed matricesconvention and initialization errorsdoesn't scale; you can mis-compute by handscoring core, boundary cells, tie cases
Golden files from a trusted tool (EMBOSS needle/water, Biopython Bio.Align.PairwiseAligner, parasail)scale, long indels, affine behaviouroracle drift; risk of coupling to the implementationlong-gap and affine cases
Metamorphic propertiescheap, always-oncan't catch a wrong-but-consistent schemeevery run

Metamorphic checks worth having: reversing both sequences leaves the score unchanged; swapping the two sequences leaves it unchanged; rescoring the returned alignment equals the reported score; inserting a gap-only column does not change the score. These are cheap and catch most traceback bugs without a golden file.

Pick hand-computed matrices for the convention-sensitive core, golden files for scale and affine gaps, and properties as the always-on layer. The one rule that decides the design: the oracle must never be the implementation under test.

Failure modes and how they are detected

  • Oracle is the implementation. Detect by running the suite against a deliberately mutated scorer; if it still passes, the oracle is coupled.
  • Snapshotting one tie path. Detect by asserting score plus rescore, as above.
  • Missing empty sequence. H(0,0) and empty-vs-nonempty: score should be the gap penalties, traceback all gaps.
  • Wrong convention. A local aligner (Smith–Waterman) returns 0 for two sequences sharing no residues; a global one (Needleman–Wunsch) returns negative. Test with unrelated sequences.
  • No long-gap case. Affine bugs only appear when a gap longer than one residue exists; include a 5-residue indel.
  • Memory regression. Gotoh with a full matrix is O(mn); check peak RSS on a 10k×10k input.
  • Platform nondeterminism. Tie-break order differs across implementations; assert score, not path.

Conventions to name explicitly in the suite: EMBOSS needle is global with default gapopen 10, gapextend 0.5; NCBI BLAST with BLOSUM62 uses gap open 11, extend 1. If the suite doesn't state which convention it targets, a correct aligner will fail it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Operate a scalable sequence-search service.

Answer

Assumptions. Queries are nucleotide or protein sequences up to a few hundred kb; the reference is a public database (NCBI nt/nr, UniProt) or a private one; callers need a result they can defend in a report months later. If the caller only needs "is this read present", the design changes.

Core answer. Put a queue in front of stateless workers and treat reference databases as immutable, versioned snapshots. Bound every request before it reaches a worker (query length cap, wall-clock timeout, memory cap, fixed parameters) and stamp every response with the snapshot ID, tool version and exact command line. Reproducibility comes from the snapshot ID; pinning the container image is the easy half and buys little on its own.

Why the same query drifts. Karlin–Altschul gives E = K·m·n·e^(−λS), linear in n, the database length. Rebuild nt and every e-value moves even though the alignment is identical: a hit at E = 1e-5 against a 100 GB snapshot becomes 2e-5 against a 200 GB one. Tool versions change seeding and filtering heuristics, and defaults differ across tools, so the same query through BLAST+ and DIAMOND is not the same experiment.

settingblastnblastpDIAMOND
e-value default10100.001
word size113—
max targets50050025
threads default11—

Trade-offs. Pinning a snapshot buys reproducibility and costs you newly deposited sequences and corrected entries; the alternative is a latest alias with on-demand re-runs, which costs storage (each nt snapshot is hundreds of GB) and a re-run budget. Decide by whether the output is a regulated report (pin) or a discovery screen (latest). Sensitivity versus latency: DIAMOND's --fast/--sensitive/--very-sensitive and MMseqs2's -s trade runtime for remote-homology recall. Use sensitive settings for "is there any homolog", fast for "which strain". And -max_target_seqs is applied during the search, not as a post-hoc top-N, so lowering it to save time can drop the true best hit (Shah et al., Bioinformatics 2018); never use it as a result cap.

Failure modes, with detection.

  • Unbounded query: a multi-Mb query against nt at the default e-value 10 runs for hours. Detect with a per-request wall-clock timeout and a queue-depth alert; mitigate by rejecting queries over a length cap and windowing long ones.
  • Partial job read as success: BLAST writes output incrementally, so an OOM-killed worker leaves a file that parses. Require a sentinel written only after exit 0, and parse the whole output.
  • Nondeterministic ordering: ties break on database order, and shard results merge in completion order. Detect by running one query twice and diffing; fix by sorting on (bitscore desc, e-value asc, subject ID) before returning.
  • Database drift: record snapshot build date and sequence count in every response; alert when the snapshot changes mid-experiment.
  • Sensitive leakage: queries may be unpublished. Keep sequences out of logs, redact traces, set a retention window.
  • No-hit ambiguity: distinguish "no HSPs", "all HSPs filtered by e-value" and "search failed". Report the pre-filter HSP count.

Scaling. BLAST+ memory-maps its database files, so workers on one host share them through page cache rather than each holding a private copy. Run one process per core with -num_threads 1 for throughput; a single query spread across many threads scales sublinearly and makes per-request accounting harder. For references too large for one host, shard the database, fan the query out, then merge and re-sort.

Python
# Python 3.11, BLAST+ 2.14
def run_blast(query: str, snapshot: str, timeout_s: int = 300) -> dict:
    if len(query) > 100_000:
        raise ValueError("query exceeds 100 kb cap")
    cmd = ["blastn", "-query", "-", "-db", snapshot,
           "-outfmt", "6 qseqid sseqid pident length evalue bitscore",
           "-evalue", "1e-5", "-max_target_seqs", "500", "-num_threads", "1"]
    p = subprocess.run(cmd, input=query, capture_output=True,
                       text=True, timeout=timeout_s)
    if p.returncode != 0:
        raise RuntimeError(p.stderr[-2000:])
    rows = [l.split("\t") for l in p.stdout.splitlines()]
    rows.sort(key=lambda r: (-float(r[5]), float(r[4]), r[1]))
    return {"snapshot": snapshot, "cmd": cmd, "hits": rows}

Curated: · Written: · Reviewed:

Difficulty: Hard