# CYK algorithm

Class Parsing with context-free grammars String ${\displaystyle {\mathcal {O}}\left(n^{3}\cdot \left|G\right|\right)}$, where: ${\displaystyle n}$ is length of the string ${\displaystyle |G|}$ is the size of the CNF grammar

In computer science, the Cocke–Younger–Kasami algorithm (alternatively called CYK, or CKY) is a parsing algorithm for context-free grammars published by Itiroo Sakai in 1961.[1][2] The algorithm is named after some of its rediscoverers: John Cocke, Daniel Younger, Tadao Kasami, and Jacob T. Schwartz. It employs bottom-up parsing and dynamic programming.

The standard version of CYK operates only on context-free grammars given in Chomsky normal form (CNF). However any context-free grammar may be algorithmically transformed into a CNF grammar expressing the same language (Sipser 1997).

The importance of the CYK algorithm stems from its high efficiency in certain situations. Using big O notation, the worst case running time of CYK is ${\displaystyle {\mathcal {O}}\left(n^{3}\cdot \left|G\right|\right)}$, where ${\displaystyle n}$ is the length of the parsed string and ${\displaystyle \left|G\right|}$ is the size of the CNF grammar ${\displaystyle G}$ (Hopcroft & Ullman 1979, p. 140). This makes it one of the most efficient [citation needed] parsing algorithms in terms of worst-case asymptotic complexity, although other algorithms exist with better average running time in many practical scenarios.

## Standard form

The dynamic programming algorithm requires the context-free grammar to be rendered into Chomsky normal form (CNF), because it tests for possibilities to split the current sequence into two smaller sequences. Any context-free grammar that does not generate the empty string can be represented in CNF using only production rules of the forms ${\displaystyle A\rightarrow \alpha }$ and ${\displaystyle A\rightarrow BC}$; to allow for the empty string, one can explicitly allow ${\displaystyle S\to \varepsilon }$, where ${\displaystyle S}$ is the start symbol.[3]

## Algorithm

### As pseudocode

The algorithm in pseudocode is as follows:

let the input be a string I consisting of n characters: a1 ... an.
let the grammar contain r nonterminal symbols R1 ... Rr, with start symbol R1.
let P[n,n,r] be an array of booleans. Initialize all elements of P to false.
let back[n,n,r] be an array of lists of backpointing triples. Initialize all elements of back to the empty list.

for each s = 1 to n
for each unit production Rv → as
set P[1,s,v] = true

for each l = 2 to n -- Length of span
for each s = 1 to n-l+1 -- Start of span
for each p = 1 to l-1 -- Partition of span
for each production Ra    → Rb Rc
if P[p,s,b] and P[l-p,s+p,c] then
set P[l,s,a] = true,
append <p,b,c> to back[l,s,a]

if P[n,1,1] is true then
I is member of language
return back -- by retracing the steps through back, one can easily construct all possible parse trees of the string.
else
return "not a member of language"


#### Probabilistic CYK (for finding the most probable parse)

Allows to recover the most probable parse given the probabilities of all productions.

let the input be a string I consisting of n characters: a1 ... an.
let the grammar contain r nonterminal symbols R1 ... Rr, with start symbol R1.
let P[n,n,r] be an array of real numbers. Initialize all elements of P to zero.
let back[n,n,r] be an array of backpointing triples.
for each s = 1 to n
for each unit production Rv →as
set P[1,s,v] = Pr(Rv →as)
for each l = 2 to n -- Length of span
for each s = 1 to n-l+1 -- Start of span
for each p = 1 to l-1 -- Partition of span
for each production Ra → Rb Rc
prob_splitting = Pr(Ra →Rb Rc) * P[p,s,b] * P[l-p,s+p,c]
if prob_splitting > P[l,s,a] then
set P[l,s,a] = prob_splitting
set back[l,s,a] = <p,b,c>

if P[n,1,1] > 0 then
find the parse tree by retracing through back
return the parse tree
else
return "not a member of language"


### As prose

In informal terms, this algorithm considers every possible substring of the input string and sets ${\displaystyle P[l,s,v]}$ to be true if the substring of length ${\displaystyle l}$ starting from ${\displaystyle s}$ can be generated from the nonterminal ${\displaystyle R_{v}}$. Once it has considered substrings of length 1, it goes on to substrings of length 2, and so on. For substrings of length 2 and greater, it considers every possible partition of the substring into two parts, and checks to see if there is some production ${\displaystyle A\to B\;C}$ such that ${\displaystyle B}$ matches the first part and ${\displaystyle C}$ matches the second part. If so, it records ${\displaystyle A}$ as matching the whole substring. Once this process is completed, the input string is generated by the grammar if the substring containing the entire input string is matched by the start symbol.

## Example

This is an example grammar:

{\displaystyle {\begin{aligned}{\ce {S}}&\ {\ce {->NP\ VP}}\\{\ce {VP}}&\ {\ce {->VP\ PP}}\\{\ce {VP}}&\ {\ce {->V\ NP}}\\{\ce {VP}}&\ {\ce {->eats}}\\{\ce {PP}}&\ {\ce {->P\ NP}}\\{\ce {NP}}&\ {\ce {->Det\ N}}\\{\ce {NP}}&\ {\ce {->she}}\\{\ce {V}}&\ {\ce {->eats}}\\{\ce {P}}&\ {\ce {->with}}\\{\ce {N}}&\ {\ce {->fish}}\\{\ce {N}}&\ {\ce {->fork}}\\{\ce {Det}}&\ {\ce {->a}}\end{aligned}}}

Now the sentence she eats a fish with a fork is analyzed using the CYK algorithm. In the following table, in ${\displaystyle P[i,j,k]}$, i is the number of the row (starting at the bottom at 1), and j is the number of the column (starting at the left at 1).

 S VP S VP PP S NP NP NP V, VP Det. N P Det N she eats a fish with a fork

For readability, the CYK table for P is represented here as a 2-dimensional matrix M containing a set of non-terminal symbols, such that Rk is in ${\displaystyle M[i,j]}$ if, and only if, ${\displaystyle P[i,j,k]}$. In the above example, since a start symbol S is in ${\displaystyle M[7,1]}$, the sentence can be generated by the grammar.

## Extensions

### Generating a parse tree

The above algorithm is a recognizer that will only determine if a sentence is in the language. It is simple to extend it into a parser that also constructs a parse tree, by storing parse tree nodes as elements of the array, instead of the boolean 1. The node is linked to the array elements that were used to produce it, so as to build the tree structure. Only one such node in each array element is needed if only one parse tree is to be produced. However, if all parse trees of an ambiguous sentence are to be kept, it is necessary to store in the array element a list of all the ways the corresponding node can be obtained in the parsing process. This is sometimes done with a second table B[n,n,r] of so-called backpointers. The end result is then a shared-forest of possible parse trees, where common trees parts are factored between the various parses. This shared forest can conveniently be read as an ambiguous grammar generating only the sentence parsed, but with the same ambiguity as the original grammar, and the same parse trees up to a very simple renaming of non-terminals, as shown by Lang (1994).

### Parsing non-CNF context-free grammars

As pointed out by Lange & Leiß (2009), the drawback of all known transformations into Chomsky normal form is that they can lead to an undesirable bloat in grammar size. The size of a grammar is the sum of the sizes of its production rules, where the size of a rule is one plus the length of its right-hand side. Using ${\displaystyle g}$ to denote the size of the original grammar, the size blow-up in the worst case may range from ${\displaystyle g^{2}}$ to ${\displaystyle 2^{2g}}$, depending on the transformation algorithm used. For the use in teaching, Lange and Leiß propose a slight generalization of the CYK algorithm, "without compromising efficiency of the algorithm, clarity of its presentation, or simplicity of proofs" (Lange & Leiß 2009).

### Parsing weighted context-free grammars

It is also possible to extend the CYK algorithm to parse strings using weighted and stochastic context-free grammars. Weights (probabilities) are then stored in the table P instead of booleans, so P[i,j,A] will contain the minimum weight (maximum probability) that the substring from i to j can be derived from A. Further extensions of the algorithm allow all parses of a string to be enumerated from lowest to highest weight (highest to lowest probability).

#### Numerical stability

When the probabilistic CYK algorithm is applied to a long string, the splitting probability can become very small due to multiplying many probabilities together. This can be dealt with by summing log-probability instead of multiplying probabilities.

### Valiant's algorithm

The worst case running time of CYK is ${\displaystyle \Theta (n^{3}\cdot |G|)}$, where n is the length of the parsed string and |G| is the size of the CNF grammar G. This makes it one of the most efficient algorithms for recognizing general context-free languages in practice. Valiant (1975) gave an extension of the CYK algorithm. His algorithm computes the same parsing table as the CYK algorithm; yet he showed that algorithms for efficient multiplication of matrices with 0-1-entries can be utilized for performing this computation.

Using the Coppersmith–Winograd algorithm for multiplying these matrices, this gives an asymptotic worst-case running time of ${\displaystyle O(n^{2.38}\cdot |G|)}$. However, the constant term hidden by the Big O Notation is so large that the Coppersmith–Winograd algorithm is only worthwhile for matrices that are too large to handle on present-day computers (Knuth 1997), and this approach requires subtraction and so is only suitable for recognition. The dependence on efficient matrix multiplication cannot be avoided altogether: Lee (2002) has proved that any parser for context-free grammars working in time ${\displaystyle O(n^{3-\varepsilon }\cdot |G|)}$ can be effectively converted into an algorithm computing the product of ${\displaystyle (n\times n)}$-matrices with 0-1-entries in time ${\displaystyle O(n^{3-\varepsilon /3})}$, and this was extended by Abboud et al.[4] to apply to a constant-size grammar.