Align two complete strings using matching letters or a letter opposite a gap, with no unequal-letter columns and no double-gap columns. Give each match score one and each gap penalty . The dynamic programming table for prefixes starts with and . Its last-column cases give the displayed recurrence, where the diagonal candidate is omitted on a mismatch. Construction takes time for positive lengths and space with full alignment traceback.
An alignment with matches has gaps and score . Therefore a longest common subsequence determines its optimum. A finite mismatch penalty would solve a different problem.
Choose one contiguous substring from each string and align them under the same matching and gap rules as global sequence alignment without mismatches. Let maximize the score over aligned suffixes of the two prefixes. Zero permits a fresh empty alignment; the other cases extend one ending at adjacent prefix indices. The answer is the largest table entry, which can occur before either input ends. Starting all boundaries at zero yields time for positive lengths. Alignment traceback stops on reaching zero.
Store one maximizing predecessor together with every table value. For alignment traceback, start at and follow these pointers:
  • emits x[i-1] opposite y[j-1]; the letters are equal because that diagonal candidate was allowed only on a match.
  • emits x[i-1] opposite a gap.
  • emits a gap opposite y[j-1].
Continue to , including boundary moves, then reverse the collected columns. Any deterministic choice among tied predecessors gives an optimal alignment. Each step decreases at least one index, so reconstruction costs additional time and output space. The full score table or predecessor table requires storage for positive lengths.
For local sequence alignment without mismatches, let maximize the score of alignments of a suffix of each prefix of lengths , allowing both suffixes to be empty. Initialize and fill
Zero starts a new alignment; the remaining candidates append the possible last columns. The same optimal-substructure argument as before proves the recurrence. Because , an alignment with a negative-scoring leading portion can be improved by dropping that portion, which is exactly what the zero reset permits.
Return , since an optimal pair of substrings may finish before either full string ends. The time is for positive input lengths, with full-table space or linear rolling-row space for the score alone. If an alignment is wanted, start alignment traceback at a maximum entry and stop at zero. No mismatching diagonal is introduced.