Sub topic 3
Using the Pumping Lemma to Show a Language Is Not Context-Free
This chapter assumes you know context-free grammars (CFGs), pushdown automata (PDAs), regular languages, and proof by contradiction. A CFL is a language generated by some CFG. A DCFL is a CFL recognised by a deterministic PDA.
Proving a language is not context-free
The pumping lemma for CFLs says that if L is context-free, there is a pumping length p such that every string z in L with |z| ≥ p splits as z = uvwxy, where |vwx| ≤ p, |vx| ≥ 1, and uv^i wx^i y is in L for every i ≥ 0.
To show L = {a^n b^n c^n | n ≥ 1} is not context-free:
- Assume L is context-free with pumping length p.
- Choose z = a^p b^p c^p.
- Because |vwx| ≤ p, the substring vwx cannot contain both an a and a c.
- So pumping changes at most two of the three letter counts, and the counts become unequal.
- Each step is a contradiction, so L is not context-free.
The CYK algorithm for membership
CYK decides whether a string belongs to a CFL. It needs the grammar in Chomsky normal form, where every rule has the form A → BC or A → a. It runs in O(n³·|G|) time for a string of length n.
def cyk(w, rules, start="S"):
n = len(w)
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)) # FalseClosure and decision properties
CFLs are closed under union, concatenation, Kleene star, reversal, homomorphism, and intersection with a regular language. They are not closed under intersection or complement in general.
DCFLs are closed under complement but not under union.
Membership, emptiness, and finiteness are decidable for CFLs. Equivalence, universality, inclusion, and ambiguity are undecidable.
The Chomsky hierarchy
GATE problem patterns and strategies
GATE questions on this topic usually fall into four patterns:
- Identify the class of a given language, such as regular, CFL, DCFL, or neither.
- Check closure: decide whether a property holds for CFLs or DCFLs.
- Apply the pumping lemma to a language such as a^n b^n c^n.
- Use the CYK table or a derivation to test membership.
Test each option against a known fact. Do not assume a property holds because it holds for regular languages.
Exercise
Is the language {a^n b^n c^m | n ≥ 0, m ≥ 0} ∩ {a^m b^n c^n | m ≥ 0, n ≥ 0} context-free?
Show answer
No. The intersection is {a^n b^n c^n | n ≥ 0}, which is not context-free by the pumping lemma. The example shows that CFLs are not closed under intersection.