Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. Edit distance: the table
    4. The table in one flat vector
    5. Needleman–Wunsch: global alignment
    6. Smith–Waterman: local alignment
    7. Only the score: two rows
    8. Which one should I use?
    9. Under the hood
    10. Common pitfalls
    11. A table one row short
    12. The smallest int as minus infinity
    13. Try it yourself

    Module 12 · C++ for bioinformatics

    12.3Sequence alignment

    Line up two DNA sequences with dynamic programming: edit distance in a flat table, global alignment with Needleman–Wunsch and a traceback that prints the result, local alignment with Smith–Waterman, and two rows instead of a whole table when you only need the score.

    About 30 minutesIntermediate

    On this page
    1. Key terms
    2. In 30 seconds
    3. Edit distance: the table
    4. The table in one flat vector
    5. Needleman–Wunsch: global alignment
    6. Smith–Waterman: local alignment
    7. Only the score: two rows
    8. Which one should I use?
    9. Under the hood
    10. Common pitfalls
    11. A table one row short
    12. The smallest int as minus infinity
    13. Try it yourself

    Key terms

    alignment
    Two sequences written one above the other, with gaps (-) inserted so that matching bases line up. It shows which bases were changed, inserted or deleted.
    gap
    A - in an alignment: a base that one sequence has and the other doesn't (an insertion or a deletion).
    edit distance
    The smallest number of single-base changes, insertions and deletions that turn one sequence into the other.
    dynamic programming
    Solving a problem by filling a table of answers to smaller versions of it, each computed from answers already in the table.
    scoring scheme
    The points an alignment gets for each column: a reward for a match, a penalty for a mismatch, a penalty for a gap.
    global alignment (Needleman–Wunsch)
    The best-scoring alignment of the two sequences from end to end.
    local alignment (Smith–Waterman)
    The best-scoring alignment of a part of one sequence with a part of the other, ignoring the rest.
    traceback
    Walking back through a filled table from the final cell, following the choices that produced each score, to recover the alignment itself.

    A read from a sequencer rarely matches the reference genome letter for letter: a base can be misread, missing, or extra. To find out how two sequences relate, you write them one above the other and slide gaps in until the matching bases line up. That’s an alignment, and finding the best one by trying every arrangement would take forever. Dynamic programming finds it by filling a table, one cell per pair of prefixes, and the table fits in one flat std::vector.

    In 30 seconds

    • Cell (i, j) of the table holds the answer for the first i bases of one sequence and the first j of the other, computed from three neighbors.
    • Store the (n + 1) × (m + 1) table in one std::vector<int>, with cell (i, j) at index i * cols + j.
    • Needleman–Wunsch aligns whole sequences; Smith–Waterman finds the best-matching parts. A traceback from the best cell recovers the alignment.
    • The cost is one step per cell: n × m. If you only need the score, keep two rows instead of the whole table.

    Edit distance: the table

    How many single-base edits turn GATTACA into GTTAC? Call the first sequence a and the second b. Cell (i, j) holds the edit distance between the first i bases of a and the first j bases of b. Row 0 and column 0 compare against nothing, so they count up: turning i bases into nothing takes i deletions. Every other cell is the smallest of three ways to get there:

    • from (i - 1, j - 1), lining up a[i - 1] with b[j - 1]: free if they’re the same base, 1 if not;
    • from (i - 1, j), deleting a[i - 1]: 1;
    • from (i, j - 1), inserting b[j - 1]: 1.
    #include <algorithm>
    #include <print>
    #include <string_view>
    #include <vector>
    
    std::string_view a = "GATTACA";
    std::string_view b = "GTTAC";
    std::size_t cols = b.size() + 1;
    std::vector<int> d((a.size() + 1) * cols);
    auto at = [&](std::size_t i, std::size_t j) -> int& {
        return d[i * cols + j];
    };
    for (std::size_t i = 0; i <= a.size(); ++i) {
        for (std::size_t j = 0; j <= b.size(); ++j) {
            if (i == 0 || j == 0) {
                at(i, j) = static_cast<int>(i + j);
            } else {
                int change = a[i - 1] == b[j - 1] ? 0 : 1;
                at(i, j) = std::min({at(i - 1, j - 1) + change,
                                     at(i - 1, j) + 1, at(i, j - 1) + 1});
            }
        }
    }
    std::print("{:4}", "");
    for (char c : b) {
        std::print("{:>3}", c);
    }
    std::println("");
    for (std::size_t i = 0; i <= a.size(); ++i) {
        std::print("{}", i == 0 ? ' ' : a[i - 1]);
        for (std::size_t j = 0; j <= b.size(); ++j) {
            std::print("{:3}", at(i, j));
        }
        std::println("");
    }
    std::println("edit distance: {}", at(a.size(), b.size()));

    Output

          G  T  T  A  C
       0  1  2  3  4  5
    G  1  0  1  2  3  4
    A  2  1  1  2  2  3
    T  3  2  1  1  2  3
    T  4  3  2  1  2  3
    A  5  4  3  2  1  2
    C  6  5  4  3  2  1
    A  7  6  5  4  3  2
    edit distance: 2

    The bottom-right cell is the answer for the whole of both sequences: two edits, deleting the first A and the last one. Check a few cells by hand. Each is the smallest of: the cell diagonally above-left (plus 1 if the bases differ), the cell above plus 1, and the cell to the left plus 1.

    std::min({x, y, z}) (from <algorithm>) takes the smallest of a list in braces. The lambda at turns a row and a column into the flat index, and returns an int& so you can both read and write the cell through it.

    The table in one flat vector

    A table whose size you only know at run time could be a vector of row vectors, but vector showed why one flat vector is better: one allocation, and the rows side by side in memory. Row i starts at index i * cols, so cell (i, j) is d[i * cols + j], and moving one row down is a jump of cols elements. Here are the first three rows of the table above in memory:

    The first three rows of the edit-distance table in one vector
    The first three rows of the edit-distance table in one vector: each row is one value; each cell's width is its size in bytes.
    Value01234567891011121314151617181920212223Size
    d[0] to d[5]: row 004 bytes14 bytes24 bytes34 bytes44 bytes54 bytes24 bytes
    d[6] to d[11]: row 1 (G)14 bytes04 bytes14 bytes24 bytes34 bytes44 bytes24 bytes
    d[12] to d[17]: row 2 (A)24 bytes14 bytes14 bytes24 bytes24 bytes34 bytes24 bytes

    Six 4-byte ints per row. Row 0 holds 0 to 5 at indexes 0 to 5; row 1, for G, holds 1, 0, 1, 2, 3, 4 at indexes 6 to 11; row 2, for A, holds 2, 1, 1, 2, 2, 3 at indexes 12 to 17. The rows follow each other with nothing in between.

    The loops fill the table row by row, left to right, which is the order it sits in memory. Each cell needs only the row above and the cell to its left, so both are always ready.

    Needleman–Wunsch: global alignment

    Edit distance counts every edit as 1. Biology needs more control: a scoring scheme rewards matches and penalizes mismatches and gaps, and the best alignment has the highest score. Needleman–Wunsch fills the same table with std::max instead of std::min. Then a traceback walks back from the bottom-right cell: at each cell it asks which neighbor its score came from, steps there, and writes down one column of the alignment.

    #include <algorithm>
    #include <print>
    #include <string>
    #include <string_view>
    #include <vector>
    
    struct Alignment {
        std::string top, middle, bottom;
        int score = 0;
    };
    
    void add_column(Alignment& out, char top, char bottom) {
        out.top += top;
        out.middle += top == bottom ? '|' : ' ';
        out.bottom += bottom;
    }
    
    Alignment global_align(std::string_view a, std::string_view b) {
        const int match = 1, mismatch = -1, gap = -1;
        std::size_t cols = b.size() + 1;
        std::vector<int> f((a.size() + 1) * cols);
        auto at = [&](std::size_t i, std::size_t j) -> int& {
            return f[i * cols + j];
        };
        auto pair = [&](std::size_t i, std::size_t j) {
            return a[i - 1] == b[j - 1] ? match : mismatch;
        };
        for (std::size_t i = 0; i <= a.size(); ++i) {
            for (std::size_t j = 0; j <= b.size(); ++j) {
                if (i == 0 || j == 0) {
                    at(i, j) = static_cast<int>(i + j) * gap;
                } else {
                    at(i, j) = std::max({at(i - 1, j - 1) + pair(i, j),
                                         at(i - 1, j) + gap, at(i, j - 1) + gap});
                }
            }
        }
        Alignment out;
        out.score = at(a.size(), b.size());
        std::size_t i = a.size(), j = b.size();
        while (i > 0 || j > 0) {
            if (i > 0 && j > 0 && at(i, j) == at(i - 1, j - 1) + pair(i, j)) {
                add_column(out, a[i - 1], b[j - 1]);
                --i;
                --j;
            } else if (i > 0 && at(i, j) == at(i - 1, j) + gap) {
                add_column(out, a[i - 1], '-');
                --i;
            } else {
                add_column(out, '-', b[j - 1]);
                --j;
            }
        }
        std::ranges::reverse(out.top);
        std::ranges::reverse(out.middle);
        std::ranges::reverse(out.bottom);
        return out;
    }
    
    int main() {
        Alignment result = global_align("GATTACA", "GCATGCG");
        std::println("{}\n{}\n{}\nscore {}", result.top, result.middle,
                     result.bottom, result.score);
    }

    Output

    G-ATTACA
    | | | |
    GCA-TGCG
    score 0
    • Row 0 and column 0 hold i * gap and j * gap: lining up the first i bases with nothing costs i gaps.
    • The traceback collects columns from the end backwards, so std::ranges::reverse turns each string around at the end. In the middle line, | marks a match and a space marks a mismatch or a gap.

    Key ideaTies have more than one answer

    Several alignments can share the best score. Which one you get depends on the order the traceback checks the neighbors: this one prefers the diagonal, then the cell above, then the cell to the left. Tools pick their own order, so two programs can print different alignments with the same score, and both are right.

    Smith–Waterman: local alignment

    Global alignment forces every base of both sequences into the result. To find where a short probe matches inside a longer sequence, or a shared region in two otherwise different ones, you want a local alignment. Smith–Waterman changes three things: no cell goes below 0, so a bad stretch starts over instead of dragging the score down; the answer is the best cell anywhere in the table; and the traceback stops at the first 0.

    #include <algorithm>
    #include <print>
    #include <string>
    #include <string_view>
    #include <vector>
    
    struct Alignment {
        std::string top, middle, bottom;
        int score = 0;
        std::size_t a_start = 0, b_start = 0;
    };
    
    void add_column(Alignment& out, char top, char bottom) {
        out.top += top;
        out.middle += top == bottom ? '|' : ' ';
        out.bottom += bottom;
    }
    
    Alignment local_align(std::string_view a, std::string_view b) {
        const int match = 3, mismatch = -3, gap = -2;
        std::size_t cols = b.size() + 1;
        std::vector<int> h((a.size() + 1) * cols); // row 0 and column 0 stay 0
        auto at = [&](std::size_t i, std::size_t j) -> int& {
            return h[i * cols + j];
        };
        auto pair = [&](std::size_t i, std::size_t j) {
            return a[i - 1] == b[j - 1] ? match : mismatch;
        };
        std::size_t bi = 0, bj = 0;
        for (std::size_t i = 1; i <= a.size(); ++i) {
            for (std::size_t j = 1; j <= b.size(); ++j) {
                at(i, j) = std::max({0, at(i - 1, j - 1) + pair(i, j),
                                     at(i - 1, j) + gap, at(i, j - 1) + gap});
                if (at(i, j) > at(bi, bj)) {
                    bi = i;
                    bj = j;
                }
            }
        }
        Alignment out;
        out.score = at(bi, bj);
        std::size_t i = bi, j = bj;
        while (at(i, j) > 0) {
            if (at(i, j) == at(i - 1, j - 1) + pair(i, j)) {
                add_column(out, a[i - 1], b[j - 1]);
                --i;
                --j;
            } else if (at(i, j) == at(i - 1, j) + gap) {
                add_column(out, a[i - 1], '-');
                --i;
            } else {
                add_column(out, '-', b[j - 1]);
                --j;
            }
        }
        std::ranges::reverse(out.top);
        std::ranges::reverse(out.middle);
        std::ranges::reverse(out.bottom);
        out.a_start = i;
        out.b_start = j;
        return out;
    }
    
    int main() {
        Alignment result = local_align("TGTTACGG", "GGTTGACTA");
        std::println("{}\n{}\n{}\nscore {}", result.top, result.middle,
                     result.bottom, result.score);
        std::println("starts at a[{}] and b[{}]", result.a_start, result.b_start);
    }

    Output

    GTT-AC
    ||| ||
    GTTGAC
    score 13
    starts at a[1] and b[1]

    The traceback stops at a cell whose score is 0, so i and j are then where the aligned parts start, counting from 0. The bases around them (T and GG in a, G and TA in b) aren’t part of the result, because they don’t add to the score. The extra G in b costs a gap (-2) but is still worth taking, because the AC after it adds two matches (+3 each).

    Only the score: two rows

    The full table takes (n + 1) × (m + 1) cells. Two sequences of 10,000 bases need 100 million ints, 400 MB here. But each row is computed only from the row above it, so if you only need the score, keep two rows and swap them after each one:

    #include <algorithm>
    #include <numeric>
    #include <print>
    #include <string_view>
    #include <utility>
    #include <vector>
    
    int edit_distance(std::string_view a, std::string_view b) {
        std::vector<int> above(b.size() + 1);
        std::vector<int> row(b.size() + 1);
        std::ranges::iota(above, 0);
        for (std::size_t i = 1; i <= a.size(); ++i) {
            row[0] = static_cast<int>(i);
            for (std::size_t j = 1; j <= b.size(); ++j) {
                int change = a[i - 1] == b[j - 1] ? 0 : 1;
                row[j] =
                    std::min({above[j - 1] + change, above[j] + 1, row[j - 1] + 1});
            }
            std::swap(above, row);
        }
        return above[b.size()];
    }
    
    int main() {
        std::println("{}", edit_distance("GATTACA", "GTTAC"));
        std::println("{}", edit_distance("ACGT", "ACGT"));
        std::println("{}", edit_distance("", "ACGT"));
    }

    Output

    2
    0
    4
    • std::ranges::iota(above, 0) (from <numeric>, C++23) fills the vector with 0, 1, 2, …: row 0 of the table.
    • std::swap(above, row) (from <utility>) swaps the two vectors’ heap blocks, not their elements, so it costs the same for any length. The new row becomes above for the next pass, and after the last pass the answer is above[b.size()].

    Two rows of 10,001 ints take about 80 KB instead of 400 MB. The price is the traceback: without the table, you can’t walk back to recover the alignment. (Hirschberg’s algorithm gets the alignment in linear memory too, by splitting the problem in half recursively.)

    Which one should I use?

    WhatWhenWhyHow
    Edit distanceYou need to know how different two sequences are, with every edit costing the same.The simplest scoring: the answer is a count of edits.std::min of three neighbors, plus 1 for each edit
    Needleman–Wunsch (global)The two sequences should match end to end: two versions of one gene, a read against the region it came from.Every base takes part, and the scores reflect biology.std::max of three neighbors, traceback from the bottom-right cell
    Smith–Waterman (local)A short sequence inside a long one, or one shared region in otherwise different sequences.Bad stretches don’t count against the part that matches.Floor every cell at 0, trace back from the best cell to the first 0
    Two rowsYou only need the score.Memory grows with one sequence’s length, not the product of both.above and row, swapped after each row

    Rule of thumb: global for sequences that should match end to end, local for finding where they match, and two rows whenever you only need the score.

    Under the hood

    Every cell takes a few comparisons, and there are (n + 1) × (m + 1) of them, so the work grows with n × m: aligning two sequences twice as long takes about four times as long. That’s fine for genes and reads, but not for a read against a whole genome of 3 billion bases. The flat table helps: the inner loop walks along a row, which sits in one contiguous run of memory, and the row above was just written, so it’s still in the processor’s cache. Beyond that, real tools combine several ideas:

    • Banded alignment. When the two sequences are known to be similar, the best path stays near the diagonal. Filling only a band of cells within k of the diagonal costs about n × k steps instead of n × m. Cells outside the band are treated as unreachable.
    • Seeds first. Aligners such as BLAST and BWA first find short exact matches (k-mers, from the previous lesson) and run the dynamic programming only around them.
    • SIMD. The cells along an anti-diagonal don’t depend on each other, so a processor can compute many of them with one instruction (SIMD covers the instructions).

    Common pitfalls

    A table one row short

    The table has one more row and one more column than the sequences have bases: row 0 and column 0 stand for the empty prefix. Forget the + 1 and the last cell is past the end of the vector. GCC’s standard library checks [] in builds without optimization (Undefined behavior explains these checks), so the program stops:

    #include <print>
    #include <string_view>
    #include <vector>
    
    std::string_view a = "GATTACA";
    std::string_view b = "GTTAC";
    std::size_t cols = b.size(); // should be b.size() + 1
    std::vector<int> d(a.size() * cols);
    d[a.size() * cols + b.size()] = 2;
    std::println("{}", d.size());

    This fails when it runs

    stl_vector.h:1263: constexpr std::vector< <template-parameter-1-1>, <template-parameter-1-2> >::reference std::vector< <template-parameter-1-1>, <template-parameter-1-2> >::operator[](size_type) [with _Tp = int; _Alloc = std::allocator<int>; reference = int&; size_type = long unsigned int]: Assertion '__n < this->size()' failed.

    The fix is cols = b.size() + 1 and (a.size() + 1) * cols cells. With optimization on, the check is gone and the write silently lands in memory that belongs to something else.

    The smallest int as minus infinity

    Banded alignment and some scoring schemes need a score for “unreachable”. The smallest int looks like a good choice, until the next step adds a gap penalty to it. That’s signed overflow, which is undefined behavior; UndefinedBehaviorSanitizer catches it:

    #include <algorithm>
    #include <limits>
    #include <print>
    
    int unreachable = std::numeric_limits<int>::min();
    int gap = -2;
    int best = std::max(unreachable + gap, 5 + gap);
    std::println("{}", best);

    This fails when it runs

    main.cpp:7:33: runtime error: signed integer overflow: -2147483648 + -2 cannot be represented in type 'int'

    std::numeric_limits<int>::min() (from <limits>) is the smallest value an int can hold. Use a value far below any real score that still has room to subtract from, such as std::numeric_limits<int>::min() / 2.

    Try it yourself

    Try it yourself

    global_score scores a short read against a longer reference from end to end with two rows, so the reference’s extra bases cost gaps. Change it so the read can fit anywhere inside the reference for free: gaps before the read’s first base and after its last base cost nothing.

    #include <algorithm>
    #include <print>
    #include <string_view>
    #include <utility>
    #include <vector>
    
    int global_score(std::string_view read, std::string_view ref) {
        const int match = 1, mismatch = -1, gap = -1;
        std::vector<int> above(ref.size() + 1);
        std::vector<int> row(ref.size() + 1);
        for (std::size_t j = 0; j <= ref.size(); ++j) {
            above[j] = static_cast<int>(j) * gap;
        }
        for (std::size_t i = 1; i <= read.size(); ++i) {
            row[0] = static_cast<int>(i) * gap;
            for (std::size_t j = 1; j <= ref.size(); ++j) {
                int pair = read[i - 1] == ref[j - 1] ? match : mismatch;
                row[j] = std::max(
                    {above[j - 1] + pair, above[j] + gap, row[j - 1] + gap});
            }
            std::swap(above, row);
        }
        return above[ref.size()];
    }
    
    int main() {
        std::println("{}", global_score("GTTAC", "ACGTTACGG"));
    }

    Expected output

    5
    Show a hint

    Gaps before the read are free, so row 0 should be all zeros instead of 0, -1, -2, …. Gaps after it are free too, so the score is the best cell anywhere in the last row: std::ranges::max(above).

    Show a solution
    #include <algorithm>
    #include <print>
    #include <string_view>
    #include <utility>
    #include <vector>
    
    int fit_score(std::string_view read, std::string_view ref) {
        const int match = 1, mismatch = -1, gap = -1;
        std::vector<int> above(ref.size() + 1); // all 0: start anywhere
        std::vector<int> row(ref.size() + 1);
        for (std::size_t i = 1; i <= read.size(); ++i) {
            row[0] = static_cast<int>(i) * gap;
            for (std::size_t j = 1; j <= ref.size(); ++j) {
                int pair = read[i - 1] == ref[j - 1] ? match : mismatch;
                row[j] = std::max(
                    {above[j - 1] + pair, above[j] + gap, row[j - 1] + gap});
            }
            std::swap(above, row);
        }
        return std::ranges::max(above); // end anywhere
    }
    
    int main() {
        std::println("{}", fit_score("GTTAC", "ACGTTACGG"));
    }

    The read GTTAC appears in the reference ACGTTACGG starting at position 2, so the best fit is five matches and no gaps: 5. The global score is lower because it also pays for the reference's four extra bases as gaps. This is called a fitting or semi-global alignment, and it's how a read is placed on a longer reference.

    Saved in this browser only.