Sub topic 14
The CYK algorithm for membership
This chapter assumes you can convert a grammar to Chomsky normal form (CNF). That means removing epsilon productions, unit productions and useless symbols. It also assumes you know what a derivation and a parse tree are. Nothing else is needed.
The membership problem
Given a context-free grammar G and a string w, is w in L(G)? A PDA answers this by simulation, but a nondeterministic PDA needs a search strategy. A leftmost-derivation search can also loop forever on grammars with epsilon or unit cycles.
The CYK algorithm (Cocke, Younger, Kasami) avoids both problems. It is a dynamic programming method that works on any CFG converted to CNF, and it always halts. This is why membership for CFLs is decidable in cubic time.
Why Chomsky normal form helps
In CNF every production has one of two shapes:
A -> B C, where B and C are variables.A -> a, where a is a terminal.
Two consequences follow:
- A string of length 1 can only be derived by a terminal rule.
- A string of length 2 or more is derived by a rule
A -> B C. B derives some prefix, and C derives the rest.
The second point gives a recurrence. A variable A derives the substring w[i..j] exactly when some rule A -> B C and some split point k satisfy both of these:
- B derives
w[i..k]. - C derives
w[k+1..j].
Every substring is built from shorter substrings. So we fill a table in order of increasing length.
The table
Let n = |w|. Define T[i][j] as the set of variables that derive the substring from position i to position j, counting from 0. The algorithm has three steps:
- Length 1. For each position i, put A in
T[i][i]ifA -> w[i]is a rule. - Longer lengths. For length = 2 up to n, and for each start i with j = i + length - 1, try every split k from i to j - 1. Add A to
T[i][j]ifA -> B Cis a rule, B is inT[i][k], and C is inT[k+1][j]. - Answer. Accept if the start symbol S is in
T[0][n-1].
Python implementation
The grammar below is a CNF grammar for { a^n b^n | n >= 1 }. The variable X stands for "S followed by B", which makes the rule S -> a S b binary.
def cyk(w, rules, start="S", derives_epsilon=False):
"""CYK membership test. rules: list of (lhs, rhs_tuple) in Chomsky normal form."""
n = len(w)
if n == 0:
return derives_epsilon # epsilon is handled outside the CNF rules
T = [[set() for _ in range(n)] for _ in range(n)]
for i, ch in enumerate(w):
for lhs, rhs in rules:
if rhs == (ch,):
T[i][i].add(lhs)
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
for k in range(i, j):
for lhs, rhs in rules:
if len(rhs) == 2 and rhs[0] in T[i][k] and rhs[1] in T[k + 1][j]:
T[i][j].add(lhs)
return start in T[0][n - 1]
rules = [
("S", ("A", "B")), ("S", ("A", "X")), ("X", ("S", "B")),
("A", ("a",)), ("B", ("b",)),
]
print(cyk("aabb", rules)) # True
print(cyk("aab", rules)) # False
print(cyk("abab", rules)) # False
print(cyk("", rules)) # FalseThe loop over length must be the outermost loop. If you iterate by start position first, the shorter substrings that a cell depends on may not be filled yet.
Worked trace on aabb
Positions are 0 to 3, and the string is a, a, b, b. Each row lists the substrings of one length.
| Length | Substring | Variables in the cell | Reason |
|---|---|---|---|
| 1 | a (0) | A | A -> a |
| 1 | a (1) | A | A -> a |
| 1 | b (2) | B | B -> b |
| 1 | b (3) | B | B -> b |
| 2 | aa | none | no rule has right side A A |
| 2 | ab | S | S -> A B |
| 2 | bb | none | no rule has right side B B |
| 3 | aab | none | splits give (A, S) and (empty, B), neither is a rule |
| 3 | abb | X | X -> S B, with S for ab and B for the last b |
| 4 | aabb | S | S -> A X, with A for the first a and X for abb |
The top cell contains S, so aabb is accepted. The cell for aab is empty. That is why the string aab is rejected: its table never reaches S in the top cell.
Complexity
- The table has about n²/2 cells.
- Each cell tries up to n split points.
- Each split checks every rule, so the cost per split is proportional to |G|, the number of rules.
The total time is O(n³ · |G|). Space is O(n²) for the table. For GATE, remember "CYK takes O(n³) for a fixed grammar", and that it requires CNF.
Getting a parse tree
CYK as written only answers yes or no. To recover a parse tree, store with each variable in a cell the rule and split point k that produced it (a back pointer). Then walk from S in T[0][n-1] downward, splitting at each stored k. If a cell holds several back pointers for the same variable, the string has more than one parse. This is a practical way to detect ambiguity on a particular string.
Edge cases and common errors
- Grammar not in CNF. Rules such as
A -> a BorA -> B C Dare silently ignored by the code above and give wrong answers. Convert first. - Epsilon. CNF has no epsilon rule, except possibly
S -> εwhen S never appears on a right side. Handle the empty string separately, as thederives_epsilonargument does. - Conversion blow-up. Conversion to CNF can square the grammar size in the worst case. The bound O(n³ · |G|) is in terms of the CNF grammar.
- Wrong loop order. Fill by increasing length, not by row of the table.
- Hand tracing. Write the table by substring length. Only split points inside the substring are legal.
Alternatives
| Method | Grammar needed | Time | Notes |
|---|---|---|---|
| CYK | CNF, any CFG | O(n³) | Simple, bottom-up, handles ambiguity |
| Earley | Any CFG | O(n³), O(n²) if unambiguous, O(n) for many deterministic grammars | No normal form needed |
| LL or LR parsing | Restricted (deterministic) grammars | O(n) | Used in compilers |
| DPDA simulation | Deterministic CFLs | O(n) | Not every CFL has a DPDA |
Exercise
Using the CNF grammar in this chapter, run CYK on w = abb. What is in the cell for the whole string, and is w accepted?
Show answer
Length 1 gives A for position 0 and B for positions 1 and 2. Length 2: ab gives S (S -> A B), and bb gives nothing. Length 3 for abb: split after position 0 gives A with the cell for bb, which is empty. Split after position 1 gives the cell for ab, which is S, with B for the last b. That would need a rule with right side S B. Here X -> S B, so X is in the cell. S is not in the cell, since no rule S -> A X applies (A with the cell for bb is empty). The top cell is {X}, which does not contain S, so abb is rejected.
Exercise
A CNF grammar has 20 rules. By what factor does the worst-case running time of CYK grow when the input length goes from 100 to 300?
Show answer
Time is proportional to n³ for a fixed grammar. Tripling n multiplies the time by 3³ = 27. The 20 rules are a fixed factor and do not change the ratio.
Exercise
Why must the loop over substring length be the outermost loop?
Show answer
A cell for length L depends on cells for shorter lengths, since each split yields two shorter substrings. Filling by increasing length guarantees every needed cell is already complete.