Computer Science and IT‹›⌂ 0:00 studied

Module 7 · 15 min read · Free chapter

Context-free grammars and pushdown automata

In short

A context-free grammar replaces one variable at a time and generates nested languages such as aⁿbⁿ. Pushdown automata, which add a stack to a finite automaton, accept exactly these languages. CFLs are closed under union, concatenation and star but not under intersection or complement, and aⁿbⁿcⁿ is not context-free.

What are you preparing for? We show the practice and previous year questions of your exam.

Start from zero: a stack of tiffins

A dabbawala collects lunch boxes and piles them in a crate, one on top of another. When he unloads, the box he put in last comes out first. A pile that works this way is called a stack, and it can be as tall as the crate allows.

Now think of brackets in a sum, such as ((2+3)×4)((2 + 3) \times 4). Every opening bracket must be closed later, and the most recent one must close first. A stack checks this perfectly: push a mark for each opening bracket and pop one for each closing bracket.

In the last chapter we saw that a finite automaton cannot check {anbn∣n≥0}\{a^n b^n \mid n \ge 0\}, because it cannot count without limit. Give the automaton a stack and the problem disappears: push one plate for each aa, pop one for each bb, and accept if the plates run out exactly at the end. That machine is a pushdown automaton, and the rules that describe such nested languages are context-free grammars.

Why it matters. Every programming language has nested brackets, blocks and expressions, so its syntax is written as a context-free grammar. The parser in a compiler is a pushdown automaton, which is why this topic appears in GATE every year in some form.

Context-free grammars, derivations and parse trees

A context-free grammar (CFG) is a 4-tuple G=(V,T,P,S)G = (V, T, P, S). Here VV is a finite set of variables, TT is the set of terminals (the alphabet), S∈VS \in V is the start symbol, and PP is a set of productions of the form A→αA \to \alpha, where AA is a single variable and α∈(V∪T)∗\alpha \in (V \cup T)^*. It is called context-free because AA can be replaced by α\alpha wherever it appears, whatever surrounds it.

Take the grammar S→aSb∣εS \to aSb \mid \varepsilon. Starting from SS, we may replace SS by aSbaSb as many times as we like and finally by ε\varepsilon. So S⇒aSb⇒aaSbb⇒aabbS \Rightarrow aSb \Rightarrow aaSbb \Rightarrow aabb, and the language of the grammar is exactly {anbn∣n≥0}\{a^n b^n \mid n \ge 0\}, which no finite automaton can accept.

When a sentential form has several variables, we must choose which to replace. A leftmost derivation always replaces the leftmost variable, and a rightmost derivation always replaces the rightmost one. For the grammar S→ABS \to AB, A→aA \to a, B→bB \to b, the leftmost derivation is S⇒AB⇒aB⇒abS \Rightarrow AB \Rightarrow aB \Rightarrow ab and the rightmost one is S⇒AB⇒Ab⇒abS \Rightarrow AB \Rightarrow Ab \Rightarrow ab.

A parse tree shows a derivation without the order of steps. The root is SS, each inner node is a variable whose children spell the right side of a production, and the leaves read left to right give the derived string, called the yield. Every parse tree corresponds to exactly one leftmost derivation and exactly one rightmost derivation.

Why it matters. A compiler does not just check that a program is valid; it builds the parse tree, because the tree shows which operation applies to which operands. Everything that follows in this chapter is about building these trees reliably.

Ambiguity

A grammar is ambiguous if some string has two or more different parse trees, or equivalently two different leftmost derivations. The classic example is the expression grammar E→E+E∣E∗E∣idE \to E + E \mid E * E \mid \mathit{id}. The string id+id∗id\mathit{id} + \mathit{id} * \mathit{id} has one tree with ++ at the root and another with ∗* at the root.

The two trees mean different things. With id\mathit{id} values 2, 3 and 4, the first tree computes 2+(3×4)=142 + (3 \times 4) = 14 and the second computes (2+3)×4=20(2 + 3) \times 4 = 20. A compiler cannot allow such a choice, so we rewrite the grammar with one variable per precedence level:

E→E+T∣T,T→T∗F∣F,F→(E)∣idE \to E + T \mid T, \qquad T \to T * F \mid F, \qquad F \to (E) \mid \mathit{id}

Now ∗* can only appear below a TT, so it always binds tighter than ++. The left recursion in E→E+TE \to E + T also makes ++ group from the left, so id+id+id\mathit{id} + \mathit{id} + \mathit{id} means (id+id)+id(\mathit{id} + \mathit{id}) + \mathit{id}.

Ambiguity is a property of a grammar, and usually another grammar for the same language removes it. Some languages, however, are inherently ambiguous: every grammar for them is ambiguous. The standard example is {aibjck∣i=j or j=k}\{a^i b^j c^k \mid i = j \text{ or } j = k\}, where strings with i=j=ki = j = k can always be derived in two ways.

There is no general algorithm to decide whether a given CFG is ambiguous. That problem is undecidable, so exam answers rely on finding two parse trees for one string, not on a mechanical test.

Why it matters. Precedence and associativity rules in every language manual come from exactly this rewriting. GATE asks you to spot ambiguous grammars and to count the parse trees of a short string.

Simplification and normal forms

Grammars written by people often contain clutter. Simplification removes it in a fixed order: first ε\varepsilon-productions A→εA \to \varepsilon, then unit productions A→BA \to B, then useless symbols. A symbol is useless if it never derives a terminal string (non-generating) or can never be reached from SS (unreachable), and the non-generating ones must be removed first.

The order matters because each step can create work for the next. Removing ε\varepsilon-productions adds new unit productions, and removing unit productions can leave symbols unreachable. Doing useless symbols in the wrong order can leave a useless symbol behind.

A grammar is in Chomsky normal form (CNF) if every production is A→BCA \to BC or A→aA \to a, with S→εS \to \varepsilon allowed only when ε\varepsilon is in the language. Parse trees in CNF are binary, which makes counting easy. A string of length n≥1n \ge 1 needs exactly n−1n - 1 steps of the form A→BCA \to BC and nn steps of the form A→aA \to a, so every derivation has exactly 2n−12n - 1 steps.

Convert S→aSb∣abS \to aSb \mid ab to CNF. First add A→aA \to a and B→bB \to b, so the rules become S→ASB∣ABS \to ASB \mid AB. Then break the long right side with a new variable CC:

S→AC∣AB,C→SB,A→a,B→bS \to AC \mid AB, \qquad C \to SB, \qquad A \to a, \qquad B \to b

The string aabbaabb has length 4, so its derivation must take 2×4−1=72 \times 4 - 1 = 7 steps. Indeed S⇒AC⇒aC⇒aSB⇒aABB⇒aaBB⇒aabB⇒aabbS \Rightarrow AC \Rightarrow aC \Rightarrow aSB \Rightarrow aABB \Rightarrow aaBB \Rightarrow aabB \Rightarrow aabb uses 7 steps.

In Greibach normal form (GNF) every production is A→aαA \to a\alpha, where aa is a terminal and α\alpha is a string of variables. Each step then produces exactly one terminal, so a string of length nn is derived in exactly nn steps. GNF is useful for building a PDA that reads one symbol per move.

Why it matters. CNF is the input format for the CYK membership algorithm, and both forms appear in GATE as "how many steps does the derivation take?". Simplification is also the first step of every proof about CFGs.

Pushdown automata: final state, empty stack, DPDA and NPDA

A pushdown automaton (PDA) is a finite automaton with a stack. Formally it is a 7-tuple (Q,Σ,Γ,δ,q0,Z0,F)(Q, \Sigma, \Gamma, \delta, q_0, Z_0, F), where Γ\Gamma is the stack alphabet and Z0Z_0 is the symbol at the bottom of the stack at the start. A move looks at the current state, the next input symbol (or ε\varepsilon) and the top of the stack, then changes state and replaces the top symbol by a string, which can push, pop or leave the stack unchanged.

Here is a PDA for {anbn∣n≥1}\{a^n b^n \mid n \ge 1\} that accepts by final state q2q_2:

δ(q0,a,Z0)={(q0,aZ0)},δ(q0,a,a)={(q0,aa)}δ(q0,b,a)={(q1,ε)},δ(q1,b,a)={(q1,ε)}δ(q1,ε,Z0)={(q2,Z0)}\begin{aligned} \delta(q_0, a, Z_0) &= \{(q_0, aZ_0)\}, & \delta(q_0, a, a) &= \{(q_0, aa)\} \\ \delta(q_0, b, a) &= \{(q_1, \varepsilon)\}, & \delta(q_1, b, a) &= \{(q_1, \varepsilon)\} \\ \delta(q_1, \varepsilon, Z_0) &= \{(q_2, Z_0)\} & & \end{aligned}

On aabbaabb the stack grows to aaZ0aaZ_0, the two bb's pop it back to Z0Z_0, and the ε\varepsilon-move enters q2q_2. On aabaab one aa is left on the stack, so q2q_2 is never reached and the string is rejected.

A PDA can accept in two ways: by final state, when the input is used up and the state is in FF, or by empty stack, when the input is used up and the stack is empty. For nondeterministic PDAs the two modes accept exactly the same languages, and those languages are exactly the context-free languages.

A deterministic PDA (DPDA) never has a choice of move. Unlike finite automata, here determinism costs power. The even palindromes {wwR∣w∈{a,b}∗}\{ww^R \mid w \in \{a, b\}^*\} need a guess about where the middle is, so they are context-free but not deterministic. With a marked middle, {wcwR}\{wcw^R\} is deterministic, because the PDA switches from pushing to popping when it sees cc.

For DPDAs, the two acceptance modes also differ. Empty-stack acceptance gives only languages with the prefix property, where no string in the language is a proper prefix of another. Every deterministic CFL has an unambiguous grammar, which is why parsers prefer them.

Why it matters. Real parsers are deterministic, so programming languages are designed to be deterministic context-free. GATE often asks which of several languages need nondeterminism.

Closure, non-closure and the pumping lemma for CFLs

Context-free languages are closed under fewer operations than regular ones. Union is easy: given grammars with start symbols S1S_1 and S2S_2, add S→S1∣S2S \to S_1 \mid S_2. Concatenation uses S→S1S2S \to S_1 S_2, and star uses S→SS1∣εS \to S S_1 \mid \varepsilon.

But CFLs are not closed under intersection. Both {anbncm∣n,m≥0}\{a^n b^n c^m \mid n, m \ge 0\} and {ambncn∣n,m≥0}\{a^m b^n c^n \mid n, m \ge 0\} are context-free, yet their intersection is {anbncn∣n≥0}\{a^n b^n c^n \mid n \ge 0\}, which is not. Since L1∩L2=L1‾∪L2‾‾L_1 \cap L_2 = \overline{\overline{L_1} \cup \overline{L_2}} and union is closed, CFLs cannot be closed under complement either.

Operation CFL DCFL
Union Yes No
Intersection No No
Complement No Yes
Intersection with a regular language Yes Yes
Concatenation and star Yes No
Reversal and homomorphism Yes No

To prove that a language is not context-free, use the pumping lemma for CFLs. If LL is context-free, there is a number pp such that every z∈Lz \in L with ∣z∣≥p\lvert z \rvert \ge p splits as z=uvwxyz = uvwxy with:

∣vwx∣≤p,∣vx∣≥1,uviwxiy∈L for every i≥0\lvert vwx \rvert \le p, \qquad \lvert vx \rvert \ge 1, \qquad uv^i wx^i y \in L \text{ for every } i \ge 0

The idea is that a tall parse tree must repeat a variable on some path. The part between the two copies can be repeated, which pumps vv and xx together.

Proof: {anbncn∣n≥0}\{a^n b^n c^n \mid n \ge 0\} is not context-free. Assume it is, with pumping length pp, and take z=apbpcpz = a^p b^p c^p. Because ∣vwx∣≤p\lvert vwx \rvert \le p, the window vwxvwx cannot touch all three blocks, so vv and xx together contain at most two of the letters aa, bb and cc. Pumping with i=2i = 2 then increases at most two of the three counts, or breaks the order of letters if vv or xx mixes two letters, so uv2wx2y∉Luv^2wx^2y \notin L, which is a contradiction.

The same lemma shows that {ww∣w∈{a,b}∗}\{ww \mid w \in \{a, b\}^*\} is not context-free. Notice the contrast with {wwR}\{ww^R\}, which is context-free, because a stack reverses naturally but cannot copy.

Why it matters. "Which of these is closed?" and "which of these is context-free?" are standard GATE one-mark questions. The intersection counter-example and the anbncna^n b^n c^n proof answer most of them.

The CYK idea and decision problems for CFLs

Given a grammar in CNF and a string ww of length nn, the CYK algorithm decides whether ww is in the language. It fills a triangular table: the cell for each substring holds every variable that can derive that substring. Short substrings come first, and a substring of length ℓ\ell is handled by trying each of its ℓ−1\ell - 1 split points and combining the cells of the two pieces through rules A→BCA \to BC.

Take the grammar S→ABS \to AB, A→AA∣aA \to AA \mid a, B→bB \to b and the string aabaab. The length-1 cells are {A}\{A\}, {A}\{A\} and {B}\{B\}. For length 2, aaaa gets {A}\{A\} from A→AAA \to AA and abab gets {S}\{S\} from S→ABS \to AB.

For the whole string, the split a⋅aba \cdot ab pairs AA with SS, which no rule produces. The split aa⋅baa \cdot b pairs AA with BB, and S→ABS \to AB puts SS in the top cell, so aabaab is in the language. There are about n22\dfrac{n^2}{2} cells and each tries up to nn splits, so CYK takes O(n3)O(n^3) time for a fixed grammar.

Several other questions about CFLs also have algorithms. Emptiness is decided by checking whether SS is generating, and finiteness by checking whether the simplified CNF grammar has a cycle among its variables. But many natural questions are undecidable for CFLs: whether two grammars generate the same language, whether a grammar generates all of Σ∗\Sigma^*, whether a grammar is ambiguous, and whether two CFLs have an empty intersection.

Why it matters. CYK shows that every CFL can be parsed in polynomial time, which is why grammars are practical at all. The list of undecidable CFL problems is a frequent GATE question, and the reasons behind it are taught with Turing machines.

Descriptive lens: how written papers ask this

Written papers ask about grammars and pushdown automata in four ways:

  1. Write a grammar or a PDA for a language given in words, and show a derivation or a run.
  2. Show that a grammar is ambiguous, and give an unambiguous grammar for the same language.
  3. Convert a grammar to Chomsky or Greibach normal form after simplifying it.
  4. Prove a closure or non-closure result, or use the pumping lemma to show that a language is not context-free.

Practice questions (our own, not previous-year questions).

  1. Design a PDA that accepts {anbn∣n≥1}\{a^n b^n \mid n \ge 1\} by empty stack, and trace its moves on aaabbbaaabbb. (10 marks)
  2. Show that the grammar E→E+E∣E∗E∣idE \to E + E \mid E * E \mid \mathit{id} is ambiguous, and write an unambiguous grammar that gives ∗* higher precedence. (10 marks)
  3. Prove that context-free languages are closed under union but not under intersection or complement. (15 marks)

Answer plan for question 3.

  • Define context-free grammars briefly, and state the claim in three parts.
  • For union, take grammars G1G_1 and G2G_2 with disjoint variables, add a new start symbol SS with S→S1∣S2S \to S_1 \mid S_2, and argue that it generates exactly L1∪L2L_1 \cup L_2.
  • For intersection, give L1={anbncm}L_1 = \{a^n b^n c^m\} and L2={ambncn}L_2 = \{a^m b^n c^n\} with a grammar for each, and show that their intersection is {anbncn}\{a^n b^n c^n\}.
  • Prove with the pumping lemma that {anbncn}\{a^n b^n c^n\} is not context-free, so intersection is not closed.
  • For complement, use the identity L1∩L2=L1‾∪L2‾‾L_1 \cap L_2 = \overline{\overline{L_1} \cup \overline{L_2}} and argue that closure under complement and union would force closure under intersection.
  • Conclude that CFLs are closed under union but not under intersection or complement, and note that intersection with a regular language is still closed.

Quick revision

  • A CFG is (V,T,P,S)(V, T, P, S) with productions A→αA \to \alpha, and S→aSb∣εS \to aSb \mid \varepsilon generates anbna^n b^n.
  • Each parse tree has exactly one leftmost and one rightmost derivation.
  • A grammar is ambiguous if one string has two parse trees, and deciding ambiguity is undecidable.
  • Simplify in the order ε\varepsilon-productions, unit productions, then useless symbols.
  • In CNF a string of length nn takes 2n−12n - 1 steps, and in GNF it takes nn steps.
  • A PDA is a finite automaton with a stack, and NPDAs accept exactly the CFLs.
  • For NPDAs, final state and empty stack are equivalent, but for DPDAs empty stack is weaker.
  • {wwR}\{ww^R\} is a CFL but not a DCFL, and {ww}\{ww\} is not a CFL at all.
  • CFLs are closed under union, concatenation, star and intersection with regular languages, but not under intersection or complement.
  • The CFL pumping lemma needs ∣vwx∣≤p\lvert vwx \rvert \le p and ∣vx∣≥1\lvert vx \rvert \ge 1.
  • CYK decides membership in O(n3)O(n^3), while equivalence and universality of CFLs are undecidable.

Check yourself

Exam-style questions on this chapter. Pick an answer to see the explanation. 0 of 15 answered

  1. The grammar S→aSb∣εS \to aSb \mid \varepsilon generates:

  2. Each parse tree corresponds to how many leftmost derivations?

  3. A grammar is ambiguous if:

  4. Whether an arbitrary context-free grammar is ambiguous is:

  5. When removing useless symbols from a CFG, the correct order is:

  6. In Chomsky normal form, a string of length 6 is derived in exactly:

  7. In Greibach normal form, a string of length nn is derived in exactly:

  8. For nondeterministic PDAs, acceptance by final state and by empty stack:

  9. Which language is context-free but NOT deterministic context-free?

  10. Context-free languages are NOT closed under:

  11. Which is closed under complement?

  12. Which language is NOT context-free?

  13. In the pumping lemma for CFLs, z=uvwxyz = uvwxy must satisfy:

  14. Which problem is undecidable for context-free grammars?

  15. The CYK algorithm for a fixed CNF grammar and a string of length nn takes:

Previous year questions

Previous year questions for UPSC CSE will appear here once each one is checked word for word against the official question paper.

Learn with AI

A tutor that asks instead of telling, a partner that argues the other side, and this chapter told through your own district.

Tell the tutor what you are stuck on. It will guide you with questions and give the answer after a few tries.

🙋 Raise a doubt or feedback

Stuck somewhere, or spotted a mistake? Write to the ExamHike team. We usually reply within a day, and you will see the reply on My progress.

Log in to ask a doubt or send feedback →

Frequently asked questions

When is a grammar ambiguous?

When some string has two different parse trees, or equivalently two different leftmost derivations.

How many steps does a CNF derivation take?

A string of length n takes exactly 2n − 1 steps in Chomsky normal form, and n steps in Greibach normal form.

Are DPDAs as powerful as NPDAs?

No. Even palindromes wwᴿ need a nondeterministic PDA, so DPDAs accept a strictly smaller class.

Are context-free languages closed under intersection?

No, but the intersection of a CFL with a regular language is always context-free.

More in this module: Theory of computation

Official sources

Facts in this chapter were checked against these official sources.

  1. GATE 2026 Computer Science and Information Technology (CS) syllabus, IIT Guwahati
  2. NPTEL Theory of Computation (IIT Kanpur, 106104148): context-free grammars, normal forms, pushdown automata and CFL properties