How to prove correctness of an algorithm

In practice, to prove an algorithm you should search a good invariant property for each loop. For example, if you compute in a given order the sum of $n$ integers with a for loop (indexed by $i$), the invariant could be : "At the end of an iteration, the $sum$ variable contains the sum of the $i$ first values". It's invariant over iterations number and always true, it's easy to prove this by recurrence on the iterations number. Afterwards you can easily conclude that, at the end of the loop, $i=n$ and thus that $sum$ is the expected sum.

Then, there is several levels of strictness, but for simple algorithms we can generally conclude promptly since the correction of the algorithm becomes almost always trivial with all the loops invariants. A very classical approach is to prove before that the algorithm finishes and after that the algorithm is correct when it ends. For complete examples you can look here. For more subtil algorithms, you can also need some mathematical theorems which provide some links beetween objects.

Your example is very close to Misra-Gries algorithm. You can look for the proof of the Misra-Gries algorithm and try to adapt it or you can try to bound the number of times the count of the most frequent number is decreased.

In general, there isn't a systematic way to find if an algorithm produces the expected output or not. Indeed, this systematic way would be an algorithm and such an algorithm can't exist (Rice's theorem).

Proving correctness of algorithm is crucial. For many problems, algorithms are very complex. The reliability of an algorithm cannot be claimed unless and until it gives the correct output for each of the valid inputs.

Tracing the output of each possible input is impossible. The correctness of an algorithm can be quickly proved by checking certain conditions.

In information theory, linguistics, and computer science, the Levenshtein distance is a string metric for measuring the difference between two sequences. Informally, the Levenshtein distance between two words is the minimum number of single-character edits (insertions, deletions or substitutions) required to change one word into the other. It is named after the Soviet mathematician Vladimir Levenshtein, who considered this distance in 1965.[1]

Levenshtein distance may also be referred to as edit distance, although that term may also denote a larger family of distance metrics known collectively as edit distance.: 32 It is closely related to pairwise string alignments.

Definition[edit]

The Levenshtein distance between two strings a,b{\displaystyle a,b}

How to prove correctness of an algorithm
(of length |a|{\displaystyle |a|}
How to prove correctness of an algorithm
and |b|{\displaystyle |b|}
How to prove correctness of an algorithm
respectively) is given by lev⁡(a,b){\displaystyle \operatorname {lev} (a,b)}
How to prove correctness of an algorithm
where

lev⁡(a,b)={|a| if |b|=0,|b| if |a|=0,lev⁡(tail⁡(a),tail⁡(b)) if a[0]=b[0],1+min{lev⁡(tail⁡(a),b)lev⁡(a,tail⁡(b))lev⁡(tail⁡(a),tail⁡(b)) otherwise,{\displaystyle \operatorname {lev} (a,b)={\begin{cases}|a|&{\text{ if }}|b|=0,\\|b|&{\text{ if }}|a|=0,\\\operatorname {lev} {\big (}\operatorname {tail} (a),\operatorname {tail} (b){\big )}&{\text{ if }}a[0]=b[0],\\1+\min {\begin{cases}\operatorname {lev} {\big (}\operatorname {tail} (a),b{\big )}\\\operatorname {lev} {\big (}a,\operatorname {tail} (b){\big )}\\\operatorname {lev} {\big (}\operatorname {tail} (a),\operatorname {tail} (b){\big )}\\\end{cases}}&{\text{ otherwise,}}\end{cases}}}

where the tail{\displaystyle \operatorname {tail} }

How to prove correctness of an algorithm
of some string x{\displaystyle x}
How to prove correctness of an algorithm
is a string of all but the first character of x{\displaystyle x}, and x[n]{\displaystyle x[n]}
How to prove correctness of an algorithm
is the n{\displaystyle n}
How to prove correctness of an algorithm
th character of the string x{\displaystyle x}, counting from 0.

Note that the first element in the minimum corresponds to deletion (from a{\displaystyle a}

How to prove correctness of an algorithm
to b{\displaystyle b}
How to prove correctness of an algorithm
), the second to insertion and the third to replacement.

This definition corresponds directly to the naive recursive implementation.

Example[edit]

Edit distance matrix for two words using cost of substitution as 1 and cost of deletion or insertion as 0.5

For example, the Levenshtein distance between "kitten" and "sitting" is 3, since the following 3 edits change one into the other, and there is no way to do it with fewer than 3 edits:

  1. kitten → sitten (substitution of "s" for "k"),
  2. sitten → sittin (substitution of "i" for "e"),
  3. sittin → sitting (insertion of "g" at the end).

Upper and lower bounds[edit]

The Levenshtein distance has several simple upper and lower bounds. These include:

  • It is at least the absolute value of the difference of the sizes of the two strings.
  • It is at most the length of the longer string.
  • It is zero if and only if the strings are equal.
  • If the strings have the same size, the Hamming distance is an upper bound on the Levenshtein distance. The Hamming distance is the number of positions at which the corresponding symbols in the two strings are different.
  • The Levenshtein distance between two strings is no greater than the sum of their Levenshtein distances from a third string (triangle inequality).

An example where the Levenshtein distance between two strings of the same length is strictly less than the Hamming distance is given by the pair "flaw" and "lawn". Here the Levenshtein distance equals 2 (delete "f" from the front; insert "n" at the end). The Hamming distance is 4.

In approximate string matching, the objective is to find matches for short strings in many longer texts, in situations where a small number of differences is to be expected. The short strings could come from a dictionary, for instance. Here, one of the strings is typically short, while the other is arbitrarily long. This has a wide range of applications, for instance, spell checkers, correction systems for optical character recognition, and software to assist natural-language translation based on translation memory.

The Levenshtein distance can also be computed between two longer strings, but the cost to compute it, which is roughly proportional to the product of the two string lengths, makes this impractical. Thus, when used to aid in fuzzy string searching in applications such as record linkage, the compared strings are usually short to help improve speed of comparisons.[citation needed]

In linguistics, the Levenshtein distance is used as a metric to quantify the linguistic distance, or how different two languages are from one another.[3] It is related to mutual intelligibility: the higher the linguistic distance, the lower the mutual intelligibility, and the lower the linguistic distance, the higher the mutual intelligibility.

Relationship with other edit distance metrics[edit]

There are other popular measures of edit distance, which are calculated using a different set of allowable edit operations. For instance,

Edit distance is usually defined as a parameterizable metric calculated with a specific set of allowed edit operations, and each operation is assigned a cost (possibly infinite). This is further generalized by DNA sequence alignment algorithms such as the Smith–Waterman algorithm, which make an operation's cost depend on where it is applied.

Computation[edit]

Recursive[edit]

This is a straightforward, but inefficient, recursive Haskell implementation of a lDistance function that takes two strings, s and t, together with their lengths, and returns the Levenshtein distance between them:

lDistance :: Eq a => [a] -> [a] -> Int
lDistance [] t = length t -- If s is empty, the distance is the number of characters in t
lDistance s [] = length s -- If t is empty, the distance is the number of characters in s
lDistance (a : s') (b : t') =
  if a == b
    then lDistance s' t' -- If the first characters are the same, they can be ignored
    else
      1
        + minimum -- Otherwise try all three possible actions and select the best one
          [ lDistance (a : s') t', -- Character is inserted (b inserted)
            lDistance s' (b : t'), -- Character is deleted  (a deleted)
            lDistance s' t' -- Character is replaced (a replaced with b)
          ]

This implementation is very inefficient because it recomputes the Levenshtein distance of the same substrings many times.

A more efficient method would never repeat the same distance calculation. For example, the Levenshtein distance of all possible suffixes might be stored in an array M{\displaystyle M}

How to prove correctness of an algorithm
, where M[i][j]{\displaystyle M[i][j]}
How to prove correctness of an algorithm
is the distance between the last i{\displaystyle i}
How to prove correctness of an algorithm
characters of string s and the last j{\displaystyle j}
How to prove correctness of an algorithm
characters of string t. The table is easy to construct one row at a time starting with row 0. When the entire table has been built, the desired distance is in the table in the last row and column, representing the distance between all of the characters in s and all the characters in t.

Iterative with full matrix[edit]

(Note: This section uses 1-based strings instead of 0-based strings.)

Computing the Levenshtein distance is based on the observation that if we reserve a matrix to hold the Levenshtein distances between all prefixes of the first string and all prefixes of the second, then we can compute the values in the matrix in a dynamic programming fashion, and thus find the distance between the two full strings as the last value computed.

This algorithm, an example of bottom-up dynamic programming, is discussed, with variants, in the 1974 article The String-to-string correction problem by Robert A. Wagner and Michael J. Fischer.[4]

This is a straightforward pseudocode implementation for a function LevenshteinDistance that takes two strings, s of length m, and t of length n, and returns the Levenshtein distance between them:

function LevenshteinDistance(char s[1..m], char t[1..n]):
  // for all i and j, d[i,j] will hold the Levenshtein distance between
  // the first i characters of s and the first j characters of t
  declare int d[0..m, 0..n]
 
  set each element in d to zero
 
  // source prefixes can be transformed into empty string by
  // dropping all characters
  for i from 1 to m:
    d[i, 0] := i
 
  // target prefixes can be reached from empty source prefix
  // by inserting every character
  for j from 1 to n:
    d[0, j] := j
 
  for j from 1 to n:
    for i from 1 to m:
      if s[i] = t[j]:
        substitutionCost := 0
      else:
        substitutionCost := 1

      d[i, j] := minimum(d[i-1, j] + 1,                   // deletion
                         d[i, j-1] + 1,                   // insertion
                         d[i-1, j-1] + substitutionCost)  // substitution
 
  return d[m, n]

Two examples of the resulting matrix (hovering over a tagged number reveals the operation performed to get that number):

kitten0123456s123456i222345t332234t443223i554323n665433g776544Saturday012345678S134567u21123456n32223456d43333445a54344444y65445554

The invariant maintained throughout the algorithm is that we can transform the initial segment s[1..i] into

function LevenshteinDistance(char s[1..m], char t[1..n]):
  // for all i and j, d[i,j] will hold the Levenshtein distance between
  // the first i characters of s and the first j characters of t
  declare int d[0..m, 0..n]
 
  set each element in d to zero
 
  // source prefixes can be transformed into empty string by
  // dropping all characters
  for i from 1 to m:
    d[i, 0] := i
 
  // target prefixes can be reached from empty source prefix
  // by inserting every character
  for j from 1 to n:
    d[0, j] := j
 
  for j from 1 to n:
    for i from 1 to m:
      if s[i] = t[j]:
        substitutionCost := 0
      else:
        substitutionCost := 1

      d[i, j] := minimum(d[i-1, j] + 1,                   // deletion
                         d[i, j-1] + 1,                   // insertion
                         d[i-1, j-1] + substitutionCost)  // substitution
 
  return d[m, n]
0 using a minimum of
function LevenshteinDistance(char s[1..m], char t[1..n]):
  // for all i and j, d[i,j] will hold the Levenshtein distance between
  // the first i characters of s and the first j characters of t
  declare int d[0..m, 0..n]
 
  set each element in d to zero
 
  // source prefixes can be transformed into empty string by
  // dropping all characters
  for i from 1 to m:
    d[i, 0] := i
 
  // target prefixes can be reached from empty source prefix
  // by inserting every character
  for j from 1 to n:
    d[0, j] := j
 
  for j from 1 to n:
    for i from 1 to m:
      if s[i] = t[j]:
        substitutionCost := 0
      else:
        substitutionCost := 1

      d[i, j] := minimum(d[i-1, j] + 1,                   // deletion
                         d[i, j-1] + 1,                   // insertion
                         d[i-1, j-1] + substitutionCost)  // substitution
 
  return d[m, n]
1 operations. At the end, the bottom-right element of the array contains the answer.

Iterative with two matrix rows[edit]

It turns out that only two rows of the table – the previous row and the current row being calculated – are needed for the construction, if one does not want to reconstruct the edited input strings.

The Levenshtein distance may be calculated iteratively using the following algorithm:[5]

function LevenshteinDistance(char s[0..m-1], char t[0..n-1]):
    // create two work vectors of integer distances
    declare int v0[n + 1]
    declare int v1[n + 1]

    // initialize v0 (the previous row of distances)
    // this row is A[0][i]: edit distance from an empty s to t;
    // that distance is the number of characters to append to  s to make t.
    for i from 0 to n:
        v0[i] = i

    for i from 0 to m - 1:
        // calculate v1 (current row distances) from the previous row v0

        // first element of v1 is A[i + 1][0]
        //   edit distance is delete (i + 1) chars from s to match empty t
        v1[0] = i + 1

        // use formula to fill in the rest of the row
        for j from 0 to n - 1:
            // calculating costs for A[i + 1][j + 1]
            deletionCost := v0[j + 1] + 1
            insertionCost := v1[j] + 1
            if s[i] = t[j]:
                substitutionCost := v0[j]
            else:
                substitutionCost := v0[j] + 1

            v1[j + 1] := minimum(deletionCost, insertionCost, substitutionCost)

        // copy v1 (current row) to v0 (previous row) for next iteration
        // since data in v1 is always invalidated, a swap without copy could be more efficient
        swap v0 with v1
    // after the last swap, the results of v1 are now in v0
    return v0[n]

Hirschberg's algorithm combines this method with divide and conquer. It can compute the optimal edit sequence, and not just the edit distance, in the same asymptotic time and space bounds.[6]

Automata[edit]

Levenshtein automata efficiently determine whether a string has an edit distance lower than a given constant from a given string.[7]

Approximation[edit]

The Levenshtein distance between two strings of length n can be approximated to within a factor

(log⁡n)O(1/ε),{\displaystyle (\log n)^{O(1/\varepsilon )},}

where ε > 0 is a free parameter to be tuned, in time O(n1 + ε).[8]

Computational complexity[edit]

It has been shown that the Levenshtein distance of two strings of length n cannot be computed in time O(n2 − ε) for any ε greater than zero unless the strong exponential time hypothesis is false.[9]