Skip to main content

Theory of Computation

CFG & PDA

CFG and PDA questions are steady GATE scorers: write or identify a grammar for a language, spot ambiguity, count derivation steps, and know exactly which languages a PDA (deterministic or not) can accept.

~5 hrs ~1.5–2 marks · Must-score 10 samples · 10 practice · 10 cards

GATE CSE context-free grammars and pushdown automata — productions, leftmost/rightmost derivations, parse trees, ambiguity and inherent ambiguity, CNF/GNF, PDA acceptance modes, CFG ↔ PDA, and DPDA vs NPDA with sample questions, flashcards and drills.

Learning outcomes

  • Write context-free grammars for standard languages and trace leftmost and rightmost derivations and parse trees
  • Detect ambiguity from a string with two parse trees and recognise inherently ambiguous languages
  • Design PDAs for a^n b^n, wcw^R, ww^R and balanced strings, and state acceptance by final state versus empty stack
  • Convert a CFG to an equivalent PDA, and distinguish DPDA, NPDA and the class of deterministic CFLs

CFG, derivations and parse trees

  • A context-free grammar is G = (V, T, P, S): variables V, terminals T, productions P of the form A → α with A ∈ V and α ∈ (V ∪ T)*, and a start symbol S. L(G) = { w ∈ T* | S ⇒* w }.
  • Leftmost derivation always expands the leftmost variable; rightmost derivation always expands the rightmost variable. In one derivation step exactly one variable is replaced.
  • A parse (derivation) tree has the start symbol at the root, variables at internal nodes, and the yield (left-to-right leaves) is the derived string. Every parse tree corresponds to exactly one leftmost and exactly one rightmost derivation.
  • The language of a CFG is a CFL. Regular grammars (right- or left-linear) are special CFGs; every regular language is context-free but not conversely.
  • Standard grammars: a^n b^n (n ≥ 0): S → aSb | ε; a^n b^(2n): S → aSbb | ε; even palindromes ww^R: S → aSa | bSb | ε; all palindromes: S → aSa | bSb | a | b | ε; #a = #b: S → aSb | bSa | SS | ε; balanced parentheses: S → (S)S | ε; a^n b^m c^n: S → aSc | B, B → bB | ε.
  • {a^i b^j | i ≠ j}: S → aSb | A | B, A → aA | a, B → bB | b (extra a’s or extra b’s).
  • Counting strings: in S → aSa | bSb | ε there are 2^k strings of length 2k. Count derivation steps from the structure: each production application is one step.

Formulas to remember

  • L(G) = { w ∈ T* | S ⇒* w }
  • yield of the parse tree = derived string
  • one leftmost + one rightmost derivation per parse tree
LanguageGrammar
{a^n b^n | n ≥ 0}S → aSb | ε
{a^n b^(2n) | n ≥ 0}S → aSbb | ε
even palindromes ww^RS → aSa | bSb | ε
all palindromesS → aSa | bSb | a | b | ε
#a(w) = #b(w)S → aSb | bSa | SS | ε
{a^n b^m c^n | n, m ≥ 0}S → aSc | B; B → bB | ε
{a^i b^j | i ≠ j}S → aSb | A | B; A → aA | a; B → bB | b

Worked example

Problem. Grammar S → aSb | SS | ε. Show that abab is generated and give a leftmost derivation.

Solution. S ⇒ SS ⇒ aSbS ⇒ abS ⇒ abaSb ⇒ abab. Here S → SS, then S → aSb, S → ε, S → aSb, S → ε. The grammar generates balanced strings with a as “(” and b as “)”.

Worked example — leftmost and rightmost derivations

  • Grammar (unambiguous): E → E + T | T; T → T * F | F; F → id | (E). String to derive: id + id * id.
  • Leftmost derivation: E ⇒ E + T ⇒ T + T ⇒ F + T ⇒ id + T ⇒ id + T * F ⇒ id + F * F ⇒ id + id * F ⇒ id + id * id. That is 8 steps; at each step the leftmost variable is replaced.
  • Rightmost derivation: E ⇒ E + T ⇒ E + T * F ⇒ E + T * id ⇒ E + F * id ⇒ E + id * id ⇒ T + id * id ⇒ F + id * id ⇒ id + id * id. Also 8 steps — every derivation of the same parse tree has the same number of steps.
  • Number of steps = number of internal (variable) nodes of the parse tree = number of production applications. The tree has 8 variable nodes and 5 leaves (id, +, id, *, id).
  • Different derivation ORDERS of one tree do not make a grammar ambiguous; ambiguity needs two different TREES (equivalently two different leftmost derivations).
  • Evaluation order is read from the tree: the subtree T * F is deeper than the root’s E + T, so the multiplication is computed first. This is how a grammar encodes precedence.
  • Short example: in S → aSb | ε the string aabb has the unique derivation S ⇒ aSb ⇒ aaSbb ⇒ aabb (3 steps, 3 variable nodes).
StepLeftmost sentential formProduction used
1E + TE → E + T
2T + TE → T
3F + TT → F
4id + TF → id
5id + T * FT → T * F
6id + F * FT → F
7id + id * FF → id
8id + id * idF → id

Worked example

Problem. For the grammar S → aSb | SS | ε, how many derivation steps does the leftmost derivation of aabb take if S ⇒ aSb ⇒ aaSbb ⇒ aabb is used? Is the grammar ambiguous?

Solution. The derivation uses S → aSb, S → aSb, S → ε: 3 steps. The grammar is ambiguous because S → SS lets one string have several trees. For instance ε has the tree S ⇒ ε (1 step) and also the tree S ⇒ SS ⇒ S ⇒ ε (3 steps: S → SS, S → ε for the left S, S → ε for the right S). These are different parse trees for the same string, so the grammar is ambiguous.

Ambiguity

  • A CFG is ambiguous if some string in L(G) has two or more distinct parse trees; equivalently two or more distinct leftmost derivations (or two distinct rightmost derivations).
  • Ambiguity is a property of the GRAMMAR. A language is inherently ambiguous if EVERY grammar generating it is ambiguous. Example: {a^i b^j c^k | i = j or j = k}. {a^n b^n} is not inherently ambiguous.
  • Classic ambiguous grammars: E → E + E | E * E | id (the string id + id * id has two parse trees: precedence and associativity are not encoded); S → SS | a; S → aS | Sa | a (aa has two trees); the dangling-else grammar.
  • Remove ambiguity by encoding precedence and associativity with layered non-terminals: E → E + T | T, T → T * F | F, F → id | (E). This grammar is unambiguous and generates the same language.
  • There is NO algorithm to decide whether an arbitrary CFG is ambiguous (the problem is undecidable). It is also undecidable whether a CFL is inherently ambiguous.
  • Unambiguous grammars: every string has exactly one parse tree, hence exactly one leftmost and exactly one rightmost derivation. Count parse trees (or leftmost derivations), not arbitrary derivations: many different derivation orders can share one parse tree.
  • LL(1) and LR(1) grammars are always unambiguous; every deterministic CFL has an unambiguous grammar (not conversely).
  • Reading the figure: in Tree 1 the multiplication is deeper (evaluated first), giving id + (id * id); in Tree 2 the addition is deeper, giving (id + id) * id. Same yield, different structure, so E → E+E | E*E | id is ambiguous.
  • Why layering works: a variable lower in the grammar (F) binds tighter than one higher up (E). Putting “* ” at the T level forces multiplication to be grouped before addition, and writing E → E + T (left recursive) makes + left associative.
  • Right recursion gives right associativity: E → T ^ E | T encodes right-associative exponentiation. Left recursion E → E + T encodes left associativity.
  • Quick test for ambiguity: a production like A → A A, A → A op A or two different recursive productions that can both derive the same short string (S → aS | Sa) is a red flag. Try the shortest possible string first.
  • Dangling else: stmt → if e then stmt | if e then stmt else stmt is ambiguous for if e then if e then s else s. Rewriting with matched and unmatched statements removes the ambiguity.
GrammarAmbiguous?Reason
S → SS | aYesaaa has two trees (left or right grouping)
E → E + E | E * E | idYesid+id*id has two trees
E → E + T | T; T → T * F | F; F → idNoprecedence and associativity encoded
S → aSb | εNoeach a^n b^n has a unique tree
S → aS | Sa | aYesaa: a·S or S·a

Worked example

Problem. Is S → SS | a ambiguous?

Solution. Yes. The string aaa has two parse trees: S → SS with the left S deriving aa and the right S deriving a, or the left S deriving a and the right S deriving aa.

Two different parse trees for id + id * id in the grammar E to E+E, E*E, id, one grouping the multiplication first and one grouping the addition first
Two parse trees for id + id * id: the same string with two structures proves the grammar is ambiguous.

Worked example — designing CFGs

  • Build grammars compositionally. Union: if S1 and S2 generate L1 and L2, add S → S1 | S2. Concatenation: S → S1 S2. Star: S → S1 S | ε. Reversal: reverse every right-hand side.
  • Nested (matching) dependencies are CFG-friendly: pairs of symbols that must match from the OUTSIDE IN are generated by a production that puts one symbol on each side, such as S → aSb or S → aSc.
  • a^n b^m c^(n+m): the a’s match the LAST c’s and the b’s match the FIRST c’s, so the pairing is nested: S → aSc | T, T → bTc | ε.
  • {a^i b^j c^k | i = j or j = k} is a union of two languages, each with one matching pair: S → S1 | S2; S1 → X C; X → aXb | ε; C → cC | ε; S2 → A Y; A → aA | ε; Y → bYc | ε. The string a^n b^n c^n is generated by both halves, so this grammar is ambiguous.
  • {a^n b^m | m ≥ n}: S → aSb | B, B → bB | ε (match n pairs, then free extra b’s). {a^n b^m | m ≤ n} is symmetric: S → aSb | A, A → aA | ε.
  • {w ∈ {a,b}* | w is NOT a palindrome} is context-free: S → aSa | bSb | aXb | bXa, X → aX | bX | ε. The outer layers match, and the first mismatch makes the rest free.
  • Impossible by a single grammar: a^n b^n c^n requires matching three counts; the PDA argument (one stack) and the CFL pumping lemma both rule it out.
LanguageGrammarIdea
L1 ∪ L2S → S1 | S2choose a branch
L1 L2S → S1 S2concatenate
L*S → S1 S | εrepeat
a^n b^m c^(n+m)S → aSc | T; T → bTc | εnested matching
a^n b^m, m ≥ nS → aSb | B; B → bB | εpairs then extras
non-palindromesS → aSa | bSb | aXb | bXa; X → aX | bX | εouter match, then first mismatch

Worked example

Problem. Write a CFG for L = {a^n b^m c^k | n + m = k} and derive abcc.

Solution. Write the string as a^n b^m c^m c^n: the a’s are matched by the LAST n c’s (outer pairs) and the b’s by the c’s just before them (inner pairs). So S → aSc | T and T → bTc | ε. Derive abcc (n = 1, m = 1): S ⇒ aSc ⇒ aTc ⇒ abTcc ⇒ abcc.

Simplification and normal forms (CNF / GNF)

  • Simplification order: (1) remove ε-productions, (2) remove unit productions A → B, (3) remove useless symbols (non-generating, then unreachable). The result generates L(G) − {ε}.
  • Chomsky Normal Form (CNF): every production is A → BC (two variables) or A → a (one terminal), and S → ε only if ε ∈ L. Every CFL without ε has a CNF grammar.
  • In CNF a string of length n ≥ 1 is derived in exactly 2n − 1 steps (n − 1 steps of type A → BC and n steps of type A → a). The parse tree is binary with 2n − 1 internal (variable) nodes.
  • Greibach Normal Form (GNF): every production is A → aα with a a terminal and α a (possibly empty) string of variables. In GNF a string of length n is derived in exactly n steps, which is useful for PDA construction and for showing there is no left recursion.
  • Membership in a CFL is decidable: CYK algorithm on a CNF grammar runs in O(n³ · |G|) time. Emptiness (does S generate any terminal string?) and finiteness are also decidable.
  • Left recursion A → Aα | β can be removed to A → βA′, A′ → αA′ | ε. The language is unchanged, and the new grammar suits top-down parsing.
  • Removing ε-productions can only lose the empty string itself: the new grammar generates L(G) − {ε}. A grammar may contain A → ε for a non-start variable even when ε ∉ L(G).

Formulas to remember

  • CNF: A → BC | a; steps for |w| = n: 2n − 1
  • GNF: A → aα; steps for |w| = n: n
  • CYK: O(n³)
Normal formProduction shapeDerivation steps for |w| = n
CNFA → BC or A → a2n − 1
GNFA → aα (α ∈ V*)n
Regular (right-linear)A → aB or A → an (or n + 1 with ε-ending)

Worked example

Problem. A CNF grammar derives a string of length 7. How many derivation steps and parse-tree variable nodes?

Solution. Steps = 2n − 1 = 13 (6 binary productions and 7 terminal productions). The parse tree therefore has 13 variable (internal) nodes and 7 leaves.

Pushdown automata — acceptance and design

  • A PDA is a 7-tuple (Q, Σ, Γ, δ, q0, Z0, F): finite control, input tape and an unbounded STACK. δ : Q × (Σ ∪ {ε}) × Γ → finite subsets of Q × Γ*. Each move reads at most one input symbol, pops the stack top and pushes a string.
  • Acceptance by final state: N accepts w if some computation consumes all of w and ends in a state of F. Acceptance by empty stack: some computation consumes w and leaves the stack empty. For NPDAs the two modes are equivalent in power (conversion in both directions exists).
  • Design of a^n b^n (n ≥ 1) — push an A for every a, switch state on the first b, pop an A per b, accept when only Z0 remains. This is deterministic.
  • Design of ww^R requires NON-determinism: the PDA must guess the middle of the string, push the first half and then match it against the second half in reverse. wcw^R is deterministic because the marker c reveals the middle.
  • #a = #b: keep the excess symbol on the stack (push on equal symbol, pop on the other). It is deterministic.
  • A stack gives one counter at a time: a PDA can match a^n b^n, a^n b^m c^n and palindromes but cannot match three counts a^n b^n c^n or copy ww.
  • A PDA with an extra stack is as powerful as a Turing machine; a PDA with no stack is a finite automaton.
  • Transition reading: δ(q, a, X) = {(p, γ)} means “in state q, reading a, with X on top: move to p and replace X by γ”, where the LEFTMOST symbol of γ becomes the new top. γ = ε pops, γ = X leaves the stack unchanged, γ = AX pushes A.
  • An instantaneous description (ID) is (state, remaining input, stack). A move is written (q, aw, Xβ) ⊢ (p, w, γβ). L(P) is defined using ⊢*: from (q0, w, Z0) to (f, ε, any) for final-state acceptance, or to (q, ε, ε) for empty-stack acceptance.
  • ε-moves let a PDA change the stack without consuming input; they are essential for guessing the middle of ww^R and for finishing a^n b^n by popping Z0.
  • The stack bottom marker Z0 prevents popping an empty stack. A PDA that blocks (no move) rejects that branch.
  • DPDA closed properties differ from PDA: DCFLs are closed under complement but not union/intersection; to complement a DPDA first make it halt on every input, then swap final and non-final states.
LanguageAccepted byDeterministic?
{a^n b^n | n ≥ 0}PDAYes (DPDA)
{w c w^R}PDAYes (DPDA)
{w ∈ {a,b}* | #a = #b}PDAYes (DPDA)
{a^n b^m c^n}PDAYes (DPDA)
{w w^R}PDANo (NPDA only)
{a^i b^j c^k | i = j or j = k}PDANo (NPDA only)
{a^n b^n c^n}, {ww}No PDA—

Worked example

Problem. Describe a PDA accepting {a^n b^n | n ≥ 1} by empty stack.

Solution. Start with Z0. On each a push A. On the first b pop an A and move to the popping state. On each further b pop an A. When the input ends, ε-move pops Z0 so that the stack is empty. Input a^n b^n empties the stack exactly when #a = #b.

A three-state PDA for a^n b^n with transitions a,Z/AZ, a,A/AA, b,A/eps and eps,Z/Z, next to a stack holding A, A and Z
PDA for a^n b^n: push A for each a, pop A for each b, accept when only Z remains.

Worked example — PDA computation trace (instantaneous descriptions)

  • Use the PDA of the stack figure: q0 —a,Z/AZ→ q0, q0 —a,A/AA→ q0, q0 —b,A/ε→ q1, q1 —b,A/ε→ q1, q1 —ε,Z/Z→ q2 (final). It accepts {a^n b^n | n ≥ 1} by final state.
  • Accepting run on aabb: (q0, aabb, Z) ⊢ (q0, abb, AZ) ⊢ (q0, bb, AAZ) ⊢ (q1, b, AZ) ⊢ (q1, ε, Z) ⊢ (q2, ε, Z). The last ID is in a final state with all input consumed, so aabb is accepted.
  • Rejecting run on aab (too many a’s): (q0, aab, Z) ⊢ (q0, ab, AZ) ⊢ (q0, b, AAZ) ⊢ (q1, ε, AZ). No ε-move exists with A on top in q1, so the machine blocks in a non-final state: rejected.
  • Rejecting run on abb (too many b’s): (q0, abb, Z) ⊢ (q0, bb, AZ) ⊢ (q1, b, Z). There is no b-move when Z is on top, so the machine blocks: rejected.
  • Determinism check: in q0 on input a the move depends only on the stack top (Z or A); in q1 the ε-move needs Z while the b-move needs A, so there is never a choice. Hence this PDA is deterministic and a^n b^n is a DCFL.
  • The length of a computation is the number of ⊢ steps: here 5 steps for aabb (2 pushes, 2 pops, 1 ε-move) — useful for counting questions.
  • Equivalent empty-stack version: replace the final ε-move by (q1, ε, Z) ⊢ (q2, ε, ε) and accept by empty stack; the language is the same.
StepInstantaneous descriptionMove
0(q0, aabb, Z)start
1(q0, abb, AZ)a,Z/AZ
2(q0, bb, AAZ)a,A/AA
3(q1, b, AZ)b,A/ε
4(q1, ε, Z)b,A/ε
5(q2, ε, Z)ε,Z/Z — accept

Worked example

Problem. Trace the PDA on the input aaabb and decide whether it accepts.

Solution. (q0, aaabb, Z) ⊢ (q0, aabb, AZ) ⊢ (q0, abb, AAZ) ⊢ (q0, bb, AAAZ) ⊢ (q1, b, AAZ) ⊢ (q1, ε, AZ). The input is consumed but the stack still holds A above Z, and there is no ε-move for A, so the machine stops in q1 (non-final). aaabb is rejected because #a ≠ #b.

GATE exam tricks — CFG ↔ PDA and DPDA vs NPDA

  • CFG → PDA (standard construction, empty-stack acceptance): ONE state q; initially push S. For each production A → α add δ(q, ε, A) ∋ (q, α); for each terminal a add δ(q, a, a) = (q, ε). The PDA simulates a leftmost derivation. The PDA is non-deterministic in general.
  • PDA → CFG: use variables [p X q] meaning “starting in state p with X on top, the stack eventually pops X and the machine reaches q”. The number of variables is O(|Q|² · |Γ|). Hence CFLs = languages accepted by NPDAs.
  • Hierarchy: Regular ⊂ DCFL ⊂ CFL. DPDAs (by final state) accept the deterministic CFLs. NPDA with empty stack ≡ NPDA with final state ≡ CFL; DPDA with final-state acceptance is strictly more powerful than DPDA with empty-stack acceptance.
  • NPDA is strictly more powerful than DPDA: ww^R is a CFL but not a DCFL. DCFLs are closed under complement; CFLs are not.
  • DPDA determinism: for every (q, a, X) at most one move, and no state where an ε-move competes with an a-move on the same stack top.
  • Which languages need unbounded counting in TWO independent ways? Those are not context-free: a^n b^n c^n, a^n b^m c^n d^m, {ww}, a^(n²), {a^p | p prime}.
  • Decision problems for CFGs: emptiness, finiteness and membership are decidable; equivalence, ambiguity, universality (L = Σ*), and whether L(G1) ∩ L(G2) = ∅ are undecidable.
  • GATE trick: for “number of derivation steps” questions, check whether the grammar is CNF (2n − 1) or GNF (n). For “is the grammar ambiguous?” search for a short string with two different trees (aa, aaa, id+id*id).
  • Reading the CFG → NPDA figure: the stack always holds the unmatched part of the current sentential form (top = leftmost symbol). A variable on top is expanded by an ε-move; a terminal on top must be matched with the next input symbol and popped.
  • Size of the CFG → PDA conversion: 1 state, |V| + |T| + 1 stack symbols (V ∪ T ∪ maybe Z0), and |P| + |T| transitions. Size of PDA → CFG: up to |Q|²·|Γ| variables — that is why the converse construction is rarely asked in full.
  • Because both constructions exist, “a language is context-free ⇔ it is accepted by some NPDA” — a bi-implication GATE uses in statements about regular ⊂ CFL.

Formulas to remember

  • CFG → PDA: δ(q, ε, A) ∋ (q, α) for A → α; δ(q, a, a) = (q, ε)
  • PDA → CFG: variables [p X q], O(|Q|² |Γ|)
  • Regular ⊂ DCFL ⊂ CFL
MachineAcceptsNotes
NPDA (final state or empty stack)All CFLsequivalent acceptance modes
DPDA (final state)DCFLsstronger than DPDA by empty stack
DPDA (empty stack)Prefix-free DCFLsno accepted string is a proper prefix of another
Finite automatonRegularno stack

Worked example

Problem. Convert S → aSb | ε to a PDA.

Solution. One state q, stack alphabet {S, a, b}, start with S on the stack. Transitions: δ(q, ε, S) = {(q, aSb), (q, ε)}, δ(q, a, a) = (q, ε), δ(q, b, b) = (q, ε). The PDA accepts by empty stack exactly a^n b^n.

The grammar S to aSb or epsilon converted to a one-state PDA with four kinds of moves, and stack snapshots for the input ab
CFG → NPDA: expand variables with ε-moves, match terminals, accept by empty stack.

Exam tips

  • To test ambiguity, try aa, aaa or a precedence string like id+id*id and draw two parse trees.
  • Use 2n − 1 for CNF and n for GNF in derivation-step questions.
  • Remember: NPDA ≠ DPDA, but acceptance by final state and by empty stack are equivalent for NPDA.
  • ww^R needs non-determinism; wcw^R, a^n b^n and #a = #b are deterministic.
  • A single stack cannot compare three counts or copy a string (a^n b^n c^n, ww are not CFL).
Exam pattern · 10 questions

GATE sample questions & answers

10 GATE-style MCQs for CFG & PDA with full explanations. Attempt each question before revealing the answer.

Q1

For the grammar S → aSb | SS | ε, which of the following strings is in L(G)?

  • A) abab
  • B) ba
  • C) aab
  • D) abb
Show answer & explanation

Answer: A

abab = (ab)(ab): S ⇒ SS ⇒ aSbS ⇒ abS ⇒ abaSb ⇒ abab. The strings ba, aab and abb are not balanced in the order a … b.

Q2 CNF: 2n − 1 steps

A grammar in Chomsky Normal Form derives a string of length 4. The number of steps in its derivation is:

  • A) 4
  • B) 7
  • C) 8
  • D) 3
Show answer & explanation

Answer: B

In CNF a string of length n needs 2n − 1 steps: n − 1 = 3 binary productions and n = 4 terminal productions, totalling 7.

Q3

The grammar S → SS | a is:

  • A) unambiguous
  • B) ambiguous, because aaa has two distinct parse trees
  • C) ambiguous because the language is infinite
  • D) not context-free
Show answer & explanation

Answer: B

aaa can be grouped as (aa)a or a(aa), giving two different parse trees, so the grammar is ambiguous.

Q4

Which of the following context-free languages cannot be accepted by a deterministic PDA?

  • A) {a^n b^n | n ≥ 0}
  • B) {w c w^R | w ∈ {a,b}*}
  • C) {w w^R | w ∈ {a,b}*}
  • D) {a^n b^m | n, m ≥ 0}
Show answer & explanation

Answer: C

A deterministic PDA cannot guess the middle of ww^R. a^n b^n, wcw^R (the marker c reveals the middle) and a*b* are all deterministic CFLs.

Q5

The number of states in the PDA obtained from a CFG using the standard construction (acceptance by empty stack) is:

  • A) 1
  • B) 2
  • C) equal to the number of variables
  • D) equal to the number of productions
Show answer & explanation

Answer: A

The construction uses a single state q: δ(q, ε, A) ∋ (q, α) for each A → α and δ(q, a, a) = (q, ε) for each terminal a.

Q6

Which of the following statements is TRUE?

  • A) NPDAs accepting by final state and by empty stack accept the same class of languages
  • B) DPDA and NPDA accept the same class of languages
  • C) Ambiguity of a CFG is decidable
  • D) Every CFL is accepted by some DPDA
Show answer & explanation

Answer: A

The two acceptance modes are equivalent for NPDAs. DPDAs are weaker than NPDAs, and ambiguity of CFGs is undecidable.

Q7

The number of strings of length 4 generated by S → aSa | bSb | ε is:

  • A) 2
  • B) 4
  • C) 8
  • D) 16
Show answer & explanation

Answer: B

These are even palindromes ww^R with |w| = 2, and there are 2² = 4 choices for w: aaaa, abba, baab, bbbb.

Q8

A context-free grammar is ambiguous if and only if some string in its language has:

  • A) two distinct leftmost derivations
  • B) a leftmost and a rightmost derivation
  • C) an infinite derivation
  • D) a derivation using the empty string
Show answer & explanation

Answer: A

Distinct parse trees correspond one-to-one with distinct leftmost derivations. Every derivable string has both a leftmost and a rightmost derivation, so option B alone proves nothing.

Q9

The language {a^i b^j c^k | i = j or j = k} is:

  • A) regular
  • B) deterministic context-free
  • C) context-free and inherently ambiguous
  • D) not context-free
Show answer & explanation

Answer: C

It is the union of {a^n b^n c^k} and {a^i b^n c^n}, both context-free, so it is a CFL. Strings a^n b^n c^n fall in both parts and force ambiguity in every grammar, so it is inherently ambiguous (and not a DCFL).

Q10

The grammar S → aSb | bSa | SS | ε generates all strings over {a, b} with equal numbers of a’s and b’s. The number of strings of length 4 in its language is:

  • A) 4
  • B) 6
  • C) 8
  • D) 16
Show answer & explanation

Answer: B

Strings of length 4 with two a’s and two b’s: C(4, 2) = 6 (aabb, abab, abba, baab, baba, bbaa).

Topic drill · 10 questions

10 practice questions — CFG & PDA

Extra page-specific practice beyond the GATE samples. Attempt all 10, then reveal answers to check your reasoning.

P1

Which grammar generates {a^n b^n | n ≥ 0}?

  • A) S → aSb | ε
  • B) S → aS | bS | ε
  • C) S → SS | ab
  • D) S → aSa | bSb | ε
Show answer & explanation

Answer: A) S → aSb | ε

Each application of S → aSb adds one a on the left and one b on the right, and S → ε ends the derivation.

P2

A CNF grammar derives a string of length 6. The number of derivation steps is:

  • A) 6
  • B) 11
  • C) 12
  • D) 5
Show answer & explanation

Answer: B) 11

2n − 1 = 2 · 6 − 1 = 11 steps (5 binary and 6 terminal productions).

P3

A GNF grammar derives a string of length 9. The number of derivation steps is:

  • A) 9
  • B) 17
  • C) 18
  • D) 8
Show answer & explanation

Answer: A) 9

Each GNF production emits exactly one terminal, so a string of length n needs n steps.

P4

The language {w c w^R | w ∈ {a,b}*} is accepted by:

  • A) a DPDA
  • B) only an NPDA
  • C) no PDA
  • D) only a finite automaton
Show answer & explanation

Answer: A) a DPDA

The marker c shows exactly where the stack should start popping, so no guessing is needed and a deterministic PDA works.

P5

Is {a^n b^m c^m d^n | n, m ≥ 1} context-free?

  • A) Yes, because stack contents can be nested
  • B) No, it needs two independent counters
  • C) No, because it is infinite
  • D) Only if n = m
Show answer & explanation

Answer: A) Yes, because stack contents can be nested

The dependencies are nested: push a’s, then b’s, pop b’s against c’s, then pop a’s against d’s. Grammar: S → aSd | aTd, T → bTc | bc.

P6

Whether an arbitrary context-free grammar is ambiguous is:

  • A) decidable in polynomial time
  • B) decidable but exponential
  • C) undecidable
  • D) decidable for all grammars in CNF
Show answer & explanation

Answer: C) undecidable

There is no algorithm that decides ambiguity for all CFGs; it is a classic undecidable problem (via the Post Correspondence Problem).

P7

For the grammar E → E + E | E * E | id, the string id + id * id has how many distinct parse trees?

  • A) 1
  • B) 2
  • C) 3
  • D) 4
Show answer & explanation

Answer: B) 2

It can be parsed as (id + id) * id or id + (id * id): exactly two parse trees.

P8

Which of the following problems for context-free grammars is decidable?

  • A) Is L(G) empty?
  • B) Are L(G1) and L(G2) equal?
  • C) Is G ambiguous?
  • D) Is L(G) = Σ*?
Show answer & explanation

Answer: A) Is L(G) empty?

Emptiness is decided by marking generating variables and checking whether S is generating. Equivalence, ambiguity and universality are undecidable.

P9

Which of the following languages is accepted by some non-deterministic PDA?

  • A) {a^n b^n c^n | n ≥ 0}
  • B) {ww | w ∈ {a,b}*}
  • C) {ww^R | w ∈ {a,b}*}
  • D) {a^n b^n c^n d^n | n ≥ 0}
Show answer & explanation

Answer: C) {ww^R | w ∈ {a,b}*}

ww^R is context-free (S → aSa | bSb | ε). The other languages require comparing more than one count or copying and are not context-free.

P10

After eliminating the ε-production from S → aSb | ε (and keeping an equivalent grammar for L − {ε}), the grammar becomes:

  • A) S → aSb | ab
  • B) S → aSb
  • C) S → ab
  • D) S → aS | b
Show answer & explanation

Answer: A) S → aSb | ab

Substituting ε for S in S → aSb gives S → ab. The new grammar S → aSb | ab generates {a^n b^n | n ≥ 1}, which is L − {ε}.

Topic FAQs

Is ambiguity a property of the grammar or the language?

Of the grammar. Many ambiguous grammars have an unambiguous equivalent. Only inherently ambiguous languages (such as {a^i b^j c^k | i = j or j = k}) have no unambiguous grammar at all.

Why is a PDA with a stack able to accept a^n b^n but not a^n b^n c^n?

The stack counts a’s and checks them against b’s, but once the b’s have popped the stack, nothing remains to compare with the c’s; a single stack cannot hold two independent counts.

Are DPDA and NPDA equivalent?

No. NPDAs accept all CFLs while DPDAs accept only the deterministic CFLs; for example ww^R is accepted by an NPDA but by no DPDA.

How many states does the PDA built from a CFG by the standard construction have?

Just one, because all the work is done by the stack: the PDA keeps the sentential form on the stack and matches terminals against the input.

Quick revision · 10 cards

10 flashcards — CFG & PDA

Hover a card to reveal the answer with a 3D flip. On touch devices, tap the card or use Show answer.

Q1 What are the four components of a context-free grammar G = (V, T, P, S)?
Q2 When is a context-free grammar called ambiguous?
Q3 What is an inherently ambiguous language?
Q4 How many derivation steps does a CNF grammar need for a string of length n?
Q5 How many derivation steps does a GNF grammar need for a string of length n?
Q6 What is the shape of productions in Chomsky Normal Form?
Q7 How does the standard CFG-to-PDA construction work?
Q8 Are acceptance by final state and by empty stack equivalent for NPDAs?
Q9 Why is NPDA more powerful than DPDA?
Q10 Which problems about context-free grammars are undecidable?