By the end of this chapter you'll be able to…

  • 1Explain why a stack is the memory nesting requires
  • 2Apply the single-nesting-versus-two-counts diagnostic
  • 3State what makes a grammar context-free
  • 4Distinguish leftmost and rightmost derivations from parse trees
  • 5Define ambiguity and distinguish it from inherent ambiguity
  • 6Remove ambiguity from an expression grammar by layering
  • 7State why testing ambiguity is undecidable
  • 8Describe a pushdown automaton and its two acceptance conditions
  • 9Explain why the two acceptance conditions differ for deterministic machines
  • 10State the equivalence of nondeterministic PDAs and context-free grammars
  • 11Explain why determinism costs power for PDAs but not for finite automata
  • 12Use the palindrome pair as the witness separating the two classes
  • 13Recall the closure properties of context-free languages
  • 14Recall the closure properties of deterministic context-free languages
  • 15Prove non-closure under intersection with the standard counterexample
  • 16Derive non-closure under complement from non-closure under intersection
  • 17State the production shapes of Chomsky and Greibach normal form
  • 18Explain why Chomsky normal form enables CYK parsing
  • 19Order the grammar simplification steps correctly
  • 20Distinguish non-generating from unreachable symbols
  • 21State which questions about context-free languages are decidable
💡
Why this chapter matters in GATE
Finite automata fail on nested structure because they cannot count, and adding one stack fixes exactly that gap. A stack is the right memory for nesting because nesting is last-in-first-out: the most recently opened bracket is the first that must close, and the most recently entered scope is the first that must exit. That match is why one stack is enough and why a second would be too much. So the diagnostic question shifts from the regular case. Instead of asking how many situations must be distinguished, ask whether the structure is a single nesting or requires two independent counts. Matching brackets is a single nesting and is context-free; requiring equal numbers of three symbol types needs two independent comparisons and is not. The second organising fact is that grammars and pushdown automata are equivalent only when the automaton is nondeterministic, because unlike the regular case determinism genuinely costs power here.

Before you start — revise these

🔗
Regular Expressions & Finite Automata
The regular languages are the base class, and every contrast here — determinism, closure, expressive power — is drawn against them.
🔗
Arrays, Stacks, Queues & Linked Lists
The stack's last-in-first-out discipline is exactly what makes it the right memory for nesting, and that is the whole reason a PDA works.

Context-Free Grammars & Pushdown Automata

Finite automata fail on nested structure because they cannot count. Adding one stack fixes exactly that gap, and the class of languages it unlocks is the context-free languages.

A stack is the right memory for nesting because nesting is last-in-first-out. The most recently opened bracket is the first that must close; the most recently entered function scope is the first that must exit. A stack's discipline matches that structure precisely, which is why one stack is enough and why a second would be too much.

So the diagnostic question shifts. For regular languages we asked how many situations must be distinguished. For context-free languages we ask: is the structure a single nesting, or does it require two independent counts?

Matching brackets is a single nesting, so it is context-free. Requiring equal numbers of as, bs and cs in that order needs two independent comparisons, and a single stack cannot hold both.

The second organising fact is that grammars and pushdown automata are equivalent, but only when the automaton is nondeterministic. Unlike the regular case, determinism genuinely costs power here, and the deterministic context-free languages form a strictly smaller class.

1. Context-Free Grammars

A grammar is a four-tuple: variables, terminals, productions and a start symbol.

Every production has a single variable on its left-hand side, which is what "context-free" means: a variable may be replaced regardless of what surrounds it.

A derivation replaces variables one at a time until only terminals remain. A leftmost derivation always expands the leftmost variable; a rightmost derivation the rightmost.

A parse tree records the structure of a derivation without recording the order. Every parse tree corresponds to exactly one leftmost derivation and one rightmost derivation, which is why parse trees rather than derivations are the right object for discussing structure.

The grammar generates , the standard non-regular language, in two productions. That compactness is the point: what a finite automaton cannot do at all, a grammar does trivially.

2. Ambiguity

A grammar is ambiguous if some string has two distinct parse trees. Equivalently, two distinct leftmost derivations.

The classic case is an expression grammar without precedence, such as . The string parses two ways, and the two trees mean different things.

Ambiguity is a property of the grammar, not the language. The same language usually has an unambiguous grammar, obtained by layering the productions so that precedence and associativity are forced by the structure.

, and , and .

This grammar generates the same language with exactly one parse tree per string, and the layering encodes that multiplication binds tighter than addition.

Some languages are inherently ambiguous, meaning every grammar for them is ambiguous. The standard example is , where strings satisfying both conditions must be derivable in two structurally different ways.

Checking whether a grammar is ambiguous is undecidable, so no algorithm can settle the question in general — which is why parser generators report conflicts rather than proving ambiguity.

3. Pushdown Automata

A PDA is a finite automaton with a stack. A move depends on the current state, the input symbol, and the top stack symbol, and it may change the state and replace the stack top with a string of symbols.

The stack is unbounded but accessible only at the top, which is exactly the restriction that makes the class context-free rather than recursively enumerable.

Two acceptance conditions exist.

Acceptance by final state ends in a designated accepting state. Acceptance by empty stack ends with nothing on the stack.

For nondeterministic PDAs the two are equivalent: any language accepted one way is accepted the other, by a construction that adds a bottom marker and a cleanup state.

For deterministic PDAs they are not equivalent. Empty-stack acceptance forces the language to be prefix-free, since once the stack empties the machine cannot continue, so it accepts strictly fewer languages.

The central theorem is that nondeterministic PDAs and context-free grammars describe exactly the same languages. The construction from grammar to PDA keeps the current sentential form's tail on the stack and expands variables as they surface.

4. Determinism Costs Power

This is the sharpest contrast with the regular case, and it is examined directly.

For finite automata, nondeterminism adds no power. For pushdown automata, it does: the deterministic context-free languages are a strict subset of the context-free languages.

The witness is the language of even-length palindromes, .

A nondeterministic PDA pushes symbols, guesses the midpoint, and then pops while matching. If the guess is right, the stack empties exactly as the input ends.

A deterministic PDA cannot make that guess. Reading left to right it has no way to know where the middle is, and by the time it could tell, it has already pushed past the point where it needed to start popping.

Adding an explicit centre marker fixes it. The language is deterministic, because the marker announces the midpoint and no guess is needed.

That single character is the whole difference between the two classes, which is why the pair appears so often.

PropertyCFLDCFL
UnionClosedNot closed
IntersectionNot closedNot closed
ComplementNot closedClosed
ConcatenationClosedNot closed
Kleene starClosedNot closed
Intersection with a regular languageClosedClosed

The closure table is the most examined content in the chapter, and the two surprises are worth stating plainly.

Context-free languages are not closed under intersection. The languages and are both context-free, but their intersection is , which is not.

Deterministic context-free languages are closed under complement but not union, which is the exact reverse of the general case. Complement works because a deterministic machine has one computation path, so accepting states can be swapped — the same argument as for DFAs.

5. Normal Forms

Two normal forms restrict the shape of productions without changing the language.

Chomsky normal form allows only and , with a single exception for if the empty string is in the language.

Its value is structural: every parse tree becomes binary, so a string of length has a derivation of exactly steps. That fixed length is what makes the CYK parsing algorithm possible, running in time by filling a table over substrings.

Greibach normal form allows only , where is a string of variables. Every production consumes exactly one terminal, so a derivation of a length- string takes exactly steps and left recursion is impossible by construction.

Converting to a normal form requires simplification first, and the order of the simplification steps matters.

Remove -productions, then unit productions, then useless symbols. Removing -productions can create new unit productions, and removing unit productions can create new useless symbols, so reversing the order leaves work undone.

A symbol is useless if it is either non-generating — it derives no terminal string — or unreachable from the start symbol. Both checks are needed, and non-generating symbols must be removed before unreachable ones, since removing a non-generating symbol can make others unreachable.

6. Decidable and Undecidable Questions

Some questions about context-free languages can be answered algorithmically and some cannot, and the boundary is examined.

QuestionDecidable?
Is a given string in ?Yes, by CYK
Is empty?Yes
Is finite?Yes
Is ambiguous?No
Is ?No
Is empty?No
Is regular?No
Is ?No

The pattern is that questions about a single grammar's basic structure are decidable, while questions comparing grammars or characterising the language are not.

Equivalence is decidable for deterministic context-free languages, which is a deep result and a standard distractor: the general case is undecidable but the deterministic case is not.

7. Worked Examples

Example 1. Write a grammar for and derive .

The condition is that there are at least as many s as s.

Split it into a matched core plus extra s on the left.

, and .

generates exactly for any , and prefixes any number of extra s.

Derive : .

Here two extra s came from and one matched pair from , giving and .

Checking the boundary cases confirms the grammar. With no recursion and no recursion the derivation is , giving the empty string with . There is no way to produce more s than s, since every comes from an production that also produces an .

Example 2. Show that is ambiguous, and give an unambiguous grammar for the same language.

The string has two distinct parse trees.

Tree 1 applies at the root, with the left child deriving and the right child deriving . This groups as .

Tree 2 applies at the root, with the left child deriving and the right deriving . This groups as .

Two distinct trees for one string means the grammar is ambiguous. Note that the two trees also mean different things, which is why ambiguity matters for a compiler.

The unambiguous version layers the productions by precedence.

, and , and .

Now has exactly one tree. The root must be , because a cannot generate a top-level ; the on the right then generates .

The layering forces multiplication to bind tighter, and the left recursion in each layer forces left associativity. The language is unchanged.

Example 3. Design a PDA for .

Use a stack to count.

Phase 1: in state , on reading push a marker. Stay in .

Phase 2: on reading the first , move to and pop one marker.

Phase 3: in , on reading pop one marker. Stay in .

Acceptance: if the input ends in with the stack containing only the bottom marker, accept.

The transitions enforce the structure. Once in no is accepted, which rules out strings like . Popping fails if the stack runs out early, which rules out more s than s. Ending with markers remaining rules out more s than s.

This PDA is deterministic, because the switch from pushing to popping is triggered by the input symbol changing from to , not by a guess. The language is therefore a deterministic context-free language.

Example 4. Why is not deterministic while is?

For , the centre marker appears exactly once and is not in the alphabet of . The PDA pushes every symbol until it reads , then switches to popping and matching.

The switch is triggered by an observable event, so no guess is needed and the machine is deterministic.

For there is no marker. Reading left to right, the machine sees only symbols from the same alphabet and has no way to detect the midpoint.

A nondeterministic PDA handles it by guessing: at every position it may either continue pushing or switch to popping. If any guess is correct, the machine accepts, and exactly one guess is correct for a genuine palindrome.

A deterministic machine must commit. If it switches too early it will have symbols left over; too late and the stack empties prematurely. Since the correct switching point depends on the total length, which is not known until the input ends, no deterministic strategy exists.

The formal proof is harder than the intuition, but the intuition is what the exam tests: the missing marker is the entire difference, and it separates the two language classes.

Example 5. Show that context-free languages are not closed under intersection.

Take two languages.

and .

Both are context-free. has grammar , , , which matches s against s with a stack and appends unrestricted s. is the mirror image.

Their intersection requires both conditions simultaneously: the and counts equal, and the and counts equal.

.

This language is not context-free, which is proved with the pumping lemma for context-free languages.

Intuitively, a single stack can hold one comparison. Matching s against s consumes the stack, leaving nothing to match the s against.

So two context-free languages intersected can produce a non-context-free one, and the class is not closed under intersection.

The consequence for complement follows immediately. If the class were closed under complement, then since it is closed under union, De Morgan's law would give closure under intersection. It is not closed under intersection, so it cannot be closed under complement either.

Example 6. Simplify the grammar , , , , then explain why the order of steps matters.

There are no -productions and no unit productions, so start with useless symbols.

Step 1: find non-generating symbols. A symbol is generating if it can derive a string of terminals.

, so generates. , so generates.

requires both and to generate, and requires . Neither has any other production, so neither nor can ever produce a terminal string. Both are non-generating.

Remove and , along with every production mentioning them. That deletes , and .

The grammar becomes , .

Step 2: find unreachable symbols. From we can reach nothing but terminals, so is now unreachable.

Remove . The final grammar is , generating the single string .

The order matters because removing non-generating symbols made unreachable. Had unreachability been checked first, would have appeared reachable through , and the second pass would have been needed anyway.

The general rule is that non-generating symbols are removed before unreachable ones, and both after -productions and unit productions, since each earlier step can create new instances of the later problems.

Summary

A stack is the memory nesting requires, because nesting is last-in-first-out. One stack gives the context-free languages; the diagnostic question is whether the structure is a single nesting or needs two independent counts.

A context-free grammar has a single variable on every left-hand side. Parse trees, not derivations, are the right object for structure, since each tree matches exactly one leftmost and one rightmost derivation.

Ambiguity means two parse trees for one string. It is a property of the grammar and is usually removable by layering for precedence, but some languages are inherently ambiguous, and testing ambiguity is undecidable.

A PDA is a finite automaton with a stack accessible only at the top. Final-state and empty-stack acceptance are equivalent for nondeterministic PDAs but not for deterministic ones, where empty-stack acceptance forces prefix-freeness.

Nondeterministic PDAs and context-free grammars are equivalent. Deterministic PDAs are strictly weaker, and against is the witness: the centre marker removes the guess.

Context-free languages are closed under union, concatenation, star and intersection with a regular language, but not under intersection or complement. Deterministic context-free languages are closed under complement but not union — the exact reverse.

Chomsky normal form makes parse trees binary and enables CYK parsing at . Greibach normal form consumes one terminal per step and eliminates left recursion.

Simplify in order: -productions, then unit productions, then non-generating symbols, then unreachable ones, because each step can create instances of the next problem.

Membership, emptiness and finiteness are decidable; ambiguity, equivalence, regularity and universality are not — though equivalence is decidable for deterministic context-free languages.

Key formulas & results

Everything to memorise for the exam hall, in one card. Screenshot this for revision.

The organising tool
A STACK IS THE MEMORY NESTING REQUIRES, BECAUSE NESTING IS LAST-IN-FIRST-OUT. ONE STACK GIVES EXACTLY THE CONTEXT-FREE LANGUAGES.
ASK WHETHER THE STRUCTURE IS A SINGLE NESTING OR NEEDS TWO INDEPENDENT COUNTS. MATCHING BRACKETS IS ONE NESTING; EQUAL COUNTS OF THREE SYMBOLS IS TWO.
Context-free grammars
A FOUR-TUPLE OF VARIABLES, TERMINALS, PRODUCTIONS AND A START SYMBOL, WHERE EVERY PRODUCTION HAS A SINGLE VARIABLE ON ITS LEFT.
CONTEXT-FREE MEANS A VARIABLE MAY BE REPLACED REGARDLESS OF WHAT SURROUNDS IT, WHICH IS EXACTLY WHAT THE SINGLE-VARIABLE LEFT SIDE ENCODES.
Derivations and parse trees
A LEFTMOST DERIVATION ALWAYS EXPANDS THE LEFTMOST VARIABLE; A RIGHTMOST DERIVATION THE RIGHTMOST. A PARSE TREE RECORDS STRUCTURE WITHOUT ORDER.
EVERY PARSE TREE CORRESPONDS TO EXACTLY ONE LEFTMOST AND ONE RIGHTMOST DERIVATION, WHICH IS WHY TREES RATHER THAN DERIVATIONS ARE THE RIGHT OBJECT FOR STRUCTURE.
Ambiguity
A GRAMMAR IS AMBIGUOUS IF SOME STRING HAS TWO DISTINCT PARSE TREES, EQUIVALENTLY TWO DISTINCT LEFTMOST DERIVATIONS.
IT IS A PROPERTY OF THE GRAMMAR, NOT THE LANGUAGE, AND IS USUALLY REMOVED BY LAYERING PRODUCTIONS SO THAT PRECEDENCE IS FORCED BY THE STRUCTURE.
Inherent ambiguity
SOME LANGUAGES ARE INHERENTLY AMBIGUOUS, MEANING EVERY GRAMMAR FOR THEM IS AMBIGUOUS.
THE STANDARD EXAMPLE IS a TO THE i, b TO THE j, c TO THE k WITH i EQUAL TO j OR j EQUAL TO k. TESTING WHETHER A GRAMMAR IS AMBIGUOUS IS UNDECIDABLE.
Pushdown automata
A FINITE AUTOMATON WITH A STACK. A MOVE DEPENDS ON THE STATE, THE INPUT SYMBOL AND THE TOP STACK SYMBOL, AND MAY REPLACE THE TOP WITH A STRING.
THE STACK IS UNBOUNDED BUT ACCESSIBLE ONLY AT THE TOP, WHICH IS THE RESTRICTION MAKING THE CLASS CONTEXT-FREE RATHER THAN RECURSIVELY ENUMERABLE.
The two acceptance conditions
ACCEPTANCE BY FINAL STATE ENDS IN A DESIGNATED STATE; ACCEPTANCE BY EMPTY STACK ENDS WITH NOTHING ON THE STACK.
THEY ARE EQUIVALENT FOR NONDETERMINISTIC PDAs BUT NOT FOR DETERMINISTIC ONES, WHERE EMPTY-STACK ACCEPTANCE FORCES THE LANGUAGE TO BE PREFIX-FREE.
The equivalence theorem
NONDETERMINISTIC PUSHDOWN AUTOMATA AND CONTEXT-FREE GRAMMARS DESCRIBE EXACTLY THE SAME LANGUAGES.
THE GRAMMAR-TO-PDA CONSTRUCTION KEEPS THE CURRENT SENTENTIAL FORM'S TAIL ON THE STACK AND EXPANDS VARIABLES AS THEY SURFACE.
Determinism costs power
FOR FINITE AUTOMATA NONDETERMINISM ADDS NO POWER; FOR PUSHDOWN AUTOMATA IT DOES. THE DETERMINISTIC CONTEXT-FREE LANGUAGES ARE A STRICT SUBSET.
THIS IS THE SHARPEST CONTRAST WITH THE REGULAR CASE AND IS EXAMINED DIRECTLY.
The palindrome witness
EVEN-LENGTH PALINDROMES NEED A NONDETERMINISTIC GUESS OF THE MIDPOINT. ADDING AN EXPLICIT CENTRE MARKER MAKES THE LANGUAGE DETERMINISTIC.
THAT SINGLE CHARACTER IS THE WHOLE DIFFERENCE BETWEEN THE TWO CLASSES, WHICH IS WHY THE PAIR APPEARS SO OFTEN.
CFL closure properties
CLOSED UNDER UNION, CONCATENATION, KLEENE STAR AND INTERSECTION WITH A REGULAR LANGUAGE. NOT CLOSED UNDER INTERSECTION OR COMPLEMENT.
INTERSECTION WITH A REGULAR LANGUAGE IS CLOSED BECAUSE THE PRODUCT OF A PDA WITH A DFA IS STILL A PDA, HAVING ONLY ONE STACK.
DCFL closure properties
CLOSED UNDER COMPLEMENT BUT NOT UNDER UNION, INTERSECTION, CONCATENATION OR KLEENE STAR.
THIS IS THE EXACT REVERSE OF THE GENERAL CASE. COMPLEMENT WORKS BECAUSE A DETERMINISTIC MACHINE HAS ONE COMPUTATION PATH, SO ACCEPTING STATES CAN BE SWAPPED.
Non-closure under intersection
a TO THE n b TO THE n c TO THE m AND a TO THE m b TO THE n c TO THE n ARE BOTH CONTEXT-FREE, BUT THEIR INTERSECTION IS a TO THE n b TO THE n c TO THE n, WHICH IS NOT.
A SINGLE STACK HOLDS ONE COMPARISON. MATCHING THE FIRST PAIR CONSUMES IT, LEAVING NOTHING TO MATCH THE SECOND.
Non-closure under complement
IF THE CLASS WERE CLOSED UNDER COMPLEMENT, DE MORGAN PLUS CLOSURE UNDER UNION WOULD GIVE CLOSURE UNDER INTERSECTION.
IT IS NOT CLOSED UNDER INTERSECTION, SO IT CANNOT BE CLOSED UNDER COMPLEMENT. THIS DERIVATION IS WORTH REPRODUCING RATHER THAN MEMORISING.
Chomsky normal form
ONLY PRODUCTIONS OF THE FORM A GOES TO BC OR A GOES TO a, WITH A SINGLE EXCEPTION FOR THE START SYMBOL DERIVING THE EMPTY STRING.
EVERY PARSE TREE BECOMES BINARY, SO A STRING OF LENGTH n HAS A DERIVATION OF EXACTLY 2n MINUS 1 STEPS. THIS IS WHAT MAKES CYK PARSING POSSIBLE AT O(n CUBED).
Greibach normal form
ONLY PRODUCTIONS OF THE FORM A GOES TO a FOLLOWED BY A STRING OF VARIABLES.
EVERY PRODUCTION CONSUMES EXACTLY ONE TERMINAL, SO A LENGTH-n DERIVATION TAKES EXACTLY n STEPS AND LEFT RECURSION IS IMPOSSIBLE BY CONSTRUCTION.
Simplification order
REMOVE EPSILON-PRODUCTIONS, THEN UNIT PRODUCTIONS, THEN NON-GENERATING SYMBOLS, THEN UNREACHABLE SYMBOLS.
EACH STEP CAN CREATE NEW INSTANCES OF THE NEXT PROBLEM, SO REVERSING THE ORDER LEAVES WORK UNDONE.
Useless symbols
A SYMBOL IS USELESS IF IT IS NON-GENERATING, MEANING IT DERIVES NO TERMINAL STRING, OR UNREACHABLE FROM THE START SYMBOL.
NON-GENERATING SYMBOLS MUST BE REMOVED FIRST, SINCE DOING SO CAN MAKE OTHER SYMBOLS UNREACHABLE.
Decidable questions
MEMBERSHIP, EMPTINESS AND FINITENESS ARE DECIDABLE FOR CONTEXT-FREE GRAMMARS.
AMBIGUITY, EQUIVALENCE, INTERSECTION EMPTINESS, REGULARITY AND UNIVERSALITY ARE NOT — THOUGH EQUIVALENCE IS DECIDABLE FOR DETERMINISTIC CONTEXT-FREE LANGUAGES.
⚠️

Traps GATE sets — and how to dodge them

These are the exact option-traps and misreads that cost marks under negative marking.

WATCH OUT
Claiming context-free languages are closed under intersection
They are not. Two context-free languages can intersect to give a non-context-free one, and the standard witness is the pair matching a-with-b and b-with-c intersecting to require all three equal.
WATCH OUT
Claiming deterministic context-free languages are closed under union
They are not, even though the general class is. The deterministic class is closed under complement instead, which is the exact reverse of the general case and is a standard trap.
WATCH OUT
Treating ambiguity as a property of the language
It is a property of the grammar. Most ambiguous grammars have unambiguous equivalents obtained by layering for precedence, and only inherently ambiguous languages have none.
WATCH OUT
Assuming a deterministic PDA can recognise even-length palindromes
It cannot, because the midpoint is not observable and must be guessed. Adding a centre marker makes the language deterministic, and that single character is the entire difference.
WATCH OUT
Treating the two PDA acceptance conditions as always equivalent
They are equivalent for nondeterministic machines only. For deterministic ones, empty-stack acceptance forces prefix-freeness, since the machine cannot continue once the stack empties.
WATCH OUT
Simplifying a grammar in the wrong order
Removing epsilon-productions creates unit productions, and removing unit productions creates useless symbols. Going the other way leaves work undone and produces a grammar that is not fully simplified.
WATCH OUT
Removing unreachable symbols before non-generating ones
Removing a non-generating symbol can make others unreachable, so the generating check must come first. Doing it the other way requires a second pass to catch what the first missed.
WATCH OUT
Assuming grammar equivalence is decidable
It is undecidable for general context-free grammars. It is decidable for deterministic context-free languages, which is a deep result and the usual distractor in this question type.
WATCH OUT
Expecting Chomsky normal form to preserve the empty string automatically
The form allows only two variables or one terminal on the right, neither of which produces the empty string. A single exception permitting the start symbol to derive epsilon is added when needed.
WATCH OUT
Confusing a leftmost derivation with a parse tree
A parse tree records structure without order and corresponds to exactly one leftmost and one rightmost derivation. Two different derivation orders of the same tree do not indicate ambiguity.
WATCH OUT
Assuming intersection with a regular language breaks context-freeness
It does not. The product of a PDA with a DFA is still a PDA, because it has only one stack, so the class is closed under intersection with a regular language even though not under general intersection.
WATCH OUT
Using a second stack to fix a language a PDA cannot handle
Two stacks make the machine Turing-equivalent, which is far more than context-free. The single-stack restriction is exactly what defines the class.

Exam-pattern practice

PYQ-style questions with full solutions. Work through them as a readiness check — mark yourself honestly and get your gap report at the end.

Readiness check

Are you exam-ready for Context-Free Grammars & Pushdown Automata?

9 problems from this chapter. Try each one, reveal the worked solution, mark yourself honestly — get your gap report at the end.

9 questions~6 min

5-minute revision

The whole chapter, distilled. Read this the night before the exam.

  • A stack is the memory nesting requires.
  • One nesting is context-free; two counts are not.
  • Every production has one variable on the left.
  • A parse tree matches one leftmost and one rightmost derivation.
  • Ambiguity means two parse trees for one string.
  • Ambiguity is a grammar property, not a language property.
  • Layering productions removes expression ambiguity.
  • Some languages are inherently ambiguous.
  • Testing ambiguity is undecidable.
  • A PDA is a finite automaton plus one stack.
  • The stack is accessible only at the top.
  • Final-state and empty-stack acceptance agree for NPDAs.
  • Empty-stack acceptance forces prefix-freeness for DPDAs.
  • NPDAs and context-free grammars are equivalent.
  • Determinism costs power for PDAs but not finite automata.
  • Even-length palindromes need a guessed midpoint.
  • A centre marker makes the language deterministic.
  • CFLs are closed under union, concatenation and star.
  • CFLs are not closed under intersection or complement.
  • CFLs are closed under intersection with a regular language.
  • DCFLs are closed under complement but not union.
  • One stack holds one comparison.
  • Non-closure under complement follows from De Morgan.
  • Chomsky normal form allows only two variables or one terminal.
  • Chomsky normal form makes parse trees binary.
  • CYK parses in O(n cubed) using Chomsky normal form.
  • Greibach normal form consumes one terminal per step.
  • Greibach normal form eliminates left recursion.
  • Simplify epsilon, then unit, then useless.
  • Remove non-generating symbols before unreachable ones.
  • Membership, emptiness and finiteness are decidable.
  • Ambiguity, equivalence and regularity are not.
  • Equivalence is decidable for deterministic CFLs.

GATE question blueprint

How this topic is asked, tier by tier — so you can prep to the pattern.

Typical weightage: Theory of Computation contributes roughly 7-9 of the 72 core-CS marks; grammars and pushdown automata supply 2-3 of those across 2-3 questions

Question styleMarks eachTypical countWhat it tests
Closure properties1~1Which operations preserve context-freeness and which do not
Non-closure2~1Constructing the intersection witness and deriving complement failure
Determinism2~1The palindrome witness and why the deterministic class inverts closure
Grammar construction2~1Writing a grammar for a stated language and deriving a witness string
Ambiguity2~1Exhibiting two parse trees and removing the ambiguity
PDA design2~1Stack discipline for a stated language and whether it is deterministic
Normal forms1~1Recognising Chomsky and Greibach production shapes
Grammar simplification2~1Applying the four steps in the correct order

Exam-hall strategy

Battle-tested tips from mentors and toppers for this topic under the sectional clock.

  1. Ask whether the language needs one nesting or two independent counts.
  2. For closure questions, derive the answer from union, intersection and De Morgan rather than recalling a table.
  3. Check whether a language has an observable switching trigger before calling it deterministic.
  4. For ambiguity, exhibit two parse trees rather than two derivations.
  5. Simplify grammars in the fixed order and remove non-generating symbols before unreachable ones.
  6. Remember that intersection with a regular language is closed even though general intersection is not.
  7. Grammar and automaton counts are commonly set as NAT, which carries no negative marking, so never leave one blank.
  8. For 1-mark and 2-mark MCQs, negative marking is -1/3 and -2/3, so guess only after eliminating an option.
  9. GATE gives a single freely-navigable 180-minute window, so flag a long grammar simplification and return to it.

Beyond the exam

Where this skill shows up in the job you're competing for — and in life.

Parsing a programming language

Programming language syntax is context-free precisely because it is nested, and the parser in every compiler is a pushdown automaton in disguise.

Resolving operator precedence

Layering an expression grammar into expression, term and factor is exactly how a language specification encodes that multiplication binds tighter than addition.

Validating nested data formats

Checking that JSON or XML brackets balance requires a stack, which is why a regular expression cannot validate nesting however elaborate it is written.

Reading a parser generator's conflict report

Shift-reduce conflicts arise because the grammar is not deterministic for the chosen parsing method, which is the practical face of the deterministic-versus-general distinction.

Where else this topic is tested

Prepare once, score in every exam that asks it.

GATE DALow overlap — theory of computation is not a component of that paper
UGC NET Computer ScienceHigh overlap — grammar types, closure properties and normal forms are examined as direct recall
ISRO / BARC / DRDO computer science papersVery high overlap — closure properties, ambiguity and deterministic versus nondeterministic PDAs are recurring MCQ topics

Questions aspirants ask

Pulled from the Q&A community and mentor sessions.

Because a stack's last-in-first-out discipline matches the structure of a single nesting exactly, and nothing more. When a bracket opens, it must be closed before any bracket that opened earlier can close, which is precisely the order a stack enforces. Pushing on open and popping on close therefore tracks the nesting with no extra machinery, and the unbounded depth is handled because the stack has no size limit. The limitation is equally precise: only the top is accessible. That means the machine can maintain exactly one running comparison at a time. Matching a-counts against b-counts consumes the stack, and by the time the b's are exhausted the stack is empty, leaving nothing against which to match a third symbol group. This is why the language requiring three equal counts is not context-free, and why intersecting two context-free languages can escape the class. The boundary is sharp in both directions. Giving the machine a queue instead of a stack, or a second stack, makes it Turing-equivalent, because two stacks can simulate a tape by keeping the left half in one and the right half in the other. Removing the stack entirely leaves a finite automaton and the regular languages. So the class sits exactly at the point where one unbounded last-in-first-out memory is available, and every closure property and every non-closure property in the chapter traces back to that single design decision.

Because a language is a set of strings and says nothing about how they are derived, while ambiguity is a statement about derivations. The same set of strings can be generated by many grammars, some ambiguous and some not, so the property cannot be attached to the set itself. The expression language is the standard illustration. Writing E deriving E plus E, or E times E, or an identifier, generates every arithmetic expression, but the string with one addition and one multiplication has two parse trees, grouping either way. Layering the grammar into expression, term and factor levels generates the identical set of strings with exactly one tree per string, because a term cannot generate a top-level addition and a factor cannot generate a top-level multiplication. The layering encodes precedence structurally, and the left recursion within each layer encodes left associativity. Two qualifications matter. Some languages are inherently ambiguous, meaning no unambiguous grammar exists for them at all; the standard example requires strings satisfying two overlapping conditions to be derivable in two structurally different ways, and no reformulation avoids it. And determining whether a given grammar is ambiguous is undecidable, so no algorithm can settle the question in general. That is why parser generators report shift-reduce and reduce-reduce conflicts rather than announcing ambiguity: a conflict is evidence that the particular parsing method cannot proceed deterministically, which is a weaker and decidable condition.

Because the subset construction that determinises a finite automaton has no analogue when a stack is present. For a finite automaton, the set of states the machine might currently occupy is itself finite, so a deterministic machine can track that entire set as a single state. There are at most two to the n such sets, which is large but finite, so the construction terminates and the deterministic machine exists. For a pushdown automaton, the machine's configuration includes the stack contents, which are unbounded. Tracking the set of possible configurations would require remembering unboundedly many distinct stacks simultaneously, and a single stack cannot do that. No construction exists, and indeed none can, because the deterministic class is provably smaller. The witness makes the gap concrete. Even-length palindromes require the machine to switch from pushing to popping at the exact midpoint, and nothing in the input reveals where that is until the input ends. A nondeterministic machine guesses at every position and accepts if any guess was right, which costs nothing because acceptance requires only one successful path. A deterministic machine must commit to one switching point with no information, and any fixed strategy fails on some input. Adding an explicit centre marker removes the guess entirely and the language becomes deterministic, which is why the marked and unmarked palindrome languages are the standard pair for separating the two classes.

Derive them from two facts and one law. The two facts are that context-free languages are closed under union but not intersection, and that deterministic context-free languages are closed under complement. The law is De Morgan, which ties intersection, union and complement together so that any two of the three determine the third. For the general class: union is closed by the obvious grammar construction, adding a new start symbol with alternatives for the two originals. Intersection fails, shown by the two languages each matching one pair of symbol counts, whose intersection requires all three equal. Complement must then fail too, because closure under complement plus closure under union would give closure under intersection by De Morgan. Concatenation and star are closed by grammar constructions as straightforward as union's. Intersection with a regular language is closed, because the product of a PDA with a DFA is still a PDA with one stack. For the deterministic class the reasoning inverts. Complement is closed by the single-path argument, exactly as for DFAs, once the machine is normalised to always consume its input. Union must then fail, because closure under complement plus closure under union would again give intersection, and the same three-count witness defeats it. Intersection, concatenation and star all fail for related reasons. The memorable summary is that exactly one of complement and union survives in each class, and which one survives is determined by whether the machine has a single computation path.

Because each step can create new instances of the problem the next step addresses, so a different order leaves work undone. Removing epsilon-productions means adding, for every production mentioning a nullable variable, a copy with that variable deleted. If a production was A deriving BC and B is nullable, the new copy is A deriving C — which is a unit production that did not exist before. So epsilon-removal manufactures unit productions and must come first. Removing unit productions means replacing A deriving B with copies of all of B's productions attached to A. This can leave B with no remaining references, making it unreachable when it previously was not. So unit-removal manufactures useless symbols and must come before the useless-symbol pass. Within the useless-symbol pass the order matters again. A symbol is useless if it is non-generating, meaning it derives no terminal string, or unreachable from the start. Removing a non-generating symbol also removes every production mentioning it, which can cut the only path to some other symbol and make it unreachable. So non-generating symbols must be removed before unreachable ones. Doing it the other way round requires a second reachability pass to catch what the first missed. The worked example in this chapter shows exactly this: deleting the non-generating variable removes the production that was the only route to another variable, which then becomes unreachable and must go too.
Header Logo