Context-free grammars and derivations
Context-free grammars as generators of languages: variables, terminals, productions, derivations (leftmost, rightmost, in any order), sentential forms, parse trees and their relation to derivations, the language of a grammar, designing grammars for the standard GATE languages (a^n b^n, palindromes, balanced parentheses, equal counts, i = j or j = k), regular languages as a special case, and the usual wrong grammars.
Why it exists
Regular expressions cannot count or match nested structure: , balanced parentheses and palindromes are beyond finite automata. A context-free grammar (CFG) is the notation for exactly this: rewriting rules where a single variable is replaced regardless of its neighbours (the "context-free" part). Grammars describe the syntax of programming languages (the compiler side of this site) and, in theory, the languages accepted by pushdown automata. GATE asks: write a grammar for a language, say which language a grammar generates, count derivations or strings, and compare grammars.
Prerequisites
You need strings, concatenation and languages as sets of strings (alphabets, strings and languages).
Precise definitions
A context-free grammar is a 4-tuple :
- : a finite set of variables (nonterminals);
- : a finite set of terminals, disjoint from ;
- : a finite set of productions with and (the right side may be empty, written );
- : the start variable.
Several productions with the same left side are written together: .
Derivation step. if is a production. means zero or more steps. A string in derivable from is a sentential form; one that contains only terminals is a sentence. The language of is
A language is context-free (a CFL) if it is for some CFG .
Leftmost and rightmost derivations. In a leftmost derivation the variable replaced in every step is the leftmost variable of the sentential form; in a rightmost derivation it is the rightmost.
Parse tree. A rooted ordered tree: the root is labelled , every internal node is labelled by a variable and its children (in order) spell the right side of a production (a single child for an empty right side), and the leaves are terminals (or ). The yield is the string of the leaves read from left to right; exactly when some parse tree has yield .
How it works
Derivations and parse trees
A parse tree remembers which production was applied to which variable but not the order in which the variables were expanded. Different orders give different derivations of the same tree. Each parse tree has exactly one leftmost derivation and one rightmost derivation, so counting parse trees equals counting leftmost derivations equals counting rightmost derivations (checked by exhaustive search on 120 random grammars).
Example: with , , generates . The string has one parse tree. Its leftmost derivation expands 's before 's:
Leftmost derivation of aabbb: start
Parser run by a script, not typedLeftmost derivation (the sentential form is on the left; the string to derive is on the right).
- 1S → A B
- 2A → a A
- 3A → a
- 4B → b B
- 5B → b
Step 0
Start from S. A leftmost derivation always replaces the leftmost nonterminal of the sentential form; each step expands one node of the parse tree.
and its rightmost derivation expands the 's first:
Rightmost derivation of aabbb: start
Parser run by a script, not typedRightmost derivation (the sentential form is on the left; the string to derive is on the right).
- 1S → A B
- 2A → a A
- 3A → a
- 4B → b B
- 5B → b
Step 0
Start from S. A rightmost derivation always replaces the rightmost nonterminal of the sentential form; each step expands one node of the parse tree.
Both are the same tree. Derivations in other orders also exist: the derivation has steps, the chain (2 steps) and the chain (3 steps) can be interleaved in ways, so has 10 derivations but a single parse tree (found by exhaustive search).
With empty right sides the tree has leaves. For balanced parentheses, :
Leftmost derivation of (()()): start
Parser run by a script, not typedLeftmost derivation (the sentential form is on the left; the string to derive is on the right).
- 1S → ( S ) S
- 2S → ε
Step 0
Start from S. A leftmost derivation always replaces the leftmost nonterminal of the sentential form; each step expands one node of the parse tree.
Designing grammars
Ways to think about a language:
- Matching pairs (outside in): generates ; generates .
- Concatenation of independent parts: with , generates .
- Union: . For write with , , , .
- Unequal counts by splitting into cases: means or : , , (peel matched pairs, then at least one unmatched symbol on one side).
- Reversal / palindromes: (the middle is or one symbol); only even palindromes: drop .
- Nesting: for balanced parentheses (a balanced string is empty or a balanced string inside a pair followed by a balanced string).
- Equal numbers of and in any order: . (It is correct but ambiguous; see the next page for an unambiguous grammar.)
Grammars for the standard languages: start
Computed by a script, not typed| language | grammar | strings of length at most 10 |
|---|---|---|
| a^n b^n | ||
| a^n b^(2n) | ||
| even palindromes w w^R | ||
| all palindromes | ||
| balanced parentheses | ||
| equal numbers of a and b | ||
| a^i b^j with i ≥ j | ||
| a^i b^j with i ≠ j | ||
| a^i b^j c^k with i = j or j = k |
Step 0
Each grammar was compared with a direct description of its language on every string up to length 10 over its alphabet.
How fast the languages grow differs a lot:
How many strings of each length a grammar generates: start
Computed by a script, not typed| length | a^n b^n | even palindromes | all palindromes | balanced parentheses | equal a and b |
|---|---|---|---|---|---|
| length 0 | |||||
| length 1 | |||||
| length 2 | |||||
| length 3 | |||||
| length 4 | |||||
| length 5 | |||||
| length 6 | |||||
| length 7 | |||||
| length 8 | |||||
| length 9 | |||||
| length 10 |
Step 0
Each column is the language of one grammar: its strings up to length 10 are generated by iterating the productions until nothing new appears. The columns grow in very different ways: a^n b^n has one string for every even length, balanced parentheses the Catalan numbers, equal a and b the central binomial coefficients.
Regular languages are context-free
Every regular language has a right-linear grammar: one variable per DFA state, a production for every transition and for every accepting state. For the DFA of "ends with " this grammar generates the language and gives every string exactly one parse tree (checked on all strings up to length ). So regular languages CFLs ( is context-free and not regular).
Membership
Deciding whether is possible for every grammar: the CYK algorithm decides it in cubic time after the grammar is put in Chomsky normal form (normal forms). With -productions a sentential form can be longer than the string it finally produces, which is why normal forms first remove them.
Worked examples
EX 1Which language
Easygenerates (the version with generates ). generates . generates all strings over . generates .
EX 2A leftmost derivation
EasyWith , the string : (the last step uses ). Three steps; a string takes steps.
EX 3Write a grammar for i greater than or equal to j
Medium: first is correct but ambiguous. A cleaner grammar: , ( extra 's first, then matched pairs). Both were compared with the language on all strings up to length ; the second gives every string exactly one parse tree.
EX 4A wrong grammar
MediumA common answer for "equal numbers of and " is . It generates only strings in which every prefix has at least as many 's as 's (the balanced strings with as "(" and as ")"); has equal counts but is not generated. A correct grammar is .
EX 5Typical questions
GATE level(a) How many strings of length does generate? (). (b) How many strings of length does generate? , the fifth Catalan number (counted by program). (c) Is context-free? No (pumping lemma for CFLs, later). (d) How many derivations does a string have? Many; one leftmost, one rightmost per parse tree. (e) Which of these generates palindromes? The grammar must produce both outer symbols together and allow an empty middle or a single symbol; misses the odd ones.
Cheat box
Cheat box
- ; ; left side is a single variable.
- Parse tree one leftmost derivation one rightmost derivation; many other orders.
- : . Palindromes: . Balanced: . Equal counts: .
- Unions: . Concatenation: . Star: .
- Regular context-free (right-linear grammars).
Traps and GATE patterns
Connections
Builds on
Unlocks
Across subjects
Ambiguity is the next question about a grammar (ambiguity); normal forms and the CYK algorithm are the next tools (normal forms); the machine that accepts exactly the CFLs is the pushdown automaton (PDA); compilers use grammars of the same kind for syntax (grammar ambiguity in compilers).
PYQs
17 previous year questions from your book. I re-solved each one myself (16 by running or simulating, 1 by reasoning only); the book's key is shown next to my answer. All PYQs
If G is a grammar with productions S → SaS | aSb | bSa | SS | ε where S is the start variable, then which one of the following strings is not generated by G?
- (a)abab
- (b)aaab
- (c)abbaa
- (d)babba
Which of the following languages is generated by the given grammar? S→ aS|bS|ε
- (a){anbm | n, m >= 0}
- (b){w ε {a,b}*| w has equal number of a's and b's}
- (c){an | n >= 0} U {bn | n >= 0} U {anbn | n >= 0}
- (d){a,b}*
Consider the following context-free grammar G, where S, A, and B are the variables (non-terminals), a and b are the terminal symbols, S is the start variable, and the rules of G are described as: S → aaB | Abb A → a | aA B → b | bB Which ONE of the languages L(G) is accepted by G?
- (a)L(G) = {a2bn | n ≥ 1} ∪ {anb2 | n ≥ 1}
- (b)L(G) = {anb2n | n ≥ 1} ∪ {a2nbn | n ≥ 1}
- (c)L(G) = {anbn | n ≥ 1}
- (d)L(G) = {a2nb2n | n ≥ 1}
Consider a context-free grammar G with the following 3 rules. S → aS, S → aSbS, S → c Let w ∈ L(G). Let na (w), nb (w), nc (w) denote the number of times a, b, c occur in w, respectively. Which of the following statements is/are TRUE?
- (a)na(w) > nb(w)
- (b)na(w) > nc (w) - 2
- (c)nc(w) = nb(w) + 1
- (d)nc(w) = nb(w) * 2
Consider the context-free grammar G below S → aSb | X X → aX | Xb | a | b , where S and X are non-terminals, and a and b are terminal symbols. The starting non-terminal is S. Which one of the following statements is CORRECT?
- (a)The language generated by G is (a + b)*
- (b)The language generated by G is a*(a + b)b*
- (c)The language generated by G is a*b*(a + b)
- (d)The language generated by G is not a regular language THEORY OF COMPUTATION
Consider the following context-free grammar over the
alphabet Σ = {a, b, c} with S as the start symbol:
S → abScT | abcT
T → bT | b
Which one of the following represents the language
generated by the above grammar?- (a){(ab)n (cb)n | n >= 1}
- (b){(ab) n cb (m1) cb (m2) ....... cb(mn) |n, m1 , m2 ,....., mn >= 1}
- (c){(ab)n (cbm)n | m, n >= 1}
- (d){(ab)n (cbn)m | m, n >= 1} THEORY OF COMPUTATION
Identify the language generated by the following grammar, where S is the start variable. S → XY X → aX|a Y → aYb|ε
- (a){ambn | m >= n, n > 0}
- (b){ambn | m >= n, n > =0}
- (c){ ambn | m > n, n > =0 }
- (d){ ambn | m > n, n > 0 }
Language L1 is defined by the grammar: S1 → aS1b|ε Language L2 is defined by the grammar: S2 → abS2|ε Consider the following statements: P: L1 is regular Q: L2 is regular Which one of the following is TRUE?
- (a)Both P and Q are true
- (b)P is true and Q is false
- (c)P is false and Q is true
- (d)Both P and Q are false
Consider the following context-free grammars: G1: S → aS|B, B → b|bB G2: S → aA|bB, A → aA|B|ε, B → bB|ε. Which one of the following pairs of languages is generated by G1 and G2, respectively?
- (a){ambn | m > 0 or n > 0} and {ambn | m > 0 and n > 0}
- (b){ambn | m > 0 and n > 0} and {ambn | m > 0 or n >= 0}
- (c){ambn | m >= 0 or n > 0} and {ambn| m > 0 and n > 0}
- (d){ambn | m >= 0 and n > 0} and {ambn | m > 0 or n > 0}
S → aSa | bSb | a | b The language generated by the above grammar over the alphabet is the set of:
- (a)all palindromes
- (b)all odd length palindromes
- (c)strings that begin and end with the same symbol
- (d)all even length palindromes
A CFG G is given with the following productions where S is the start symbol,A is a non-terminal and a and b are terminals. S → aS | A A →aAb | bAa | ∈ Which of the following strings is generated by the grammar above?
- (a)aabbaba
- (b)aabaaba
- (c)abababb
- (d)aabbaab THEORY OF COMPUTATION
Consider a CFG with the following productions S → AA | B A →0A | A0 | 1 B → 0B00 | 1 S is the start symbol, A and B are non-terminals and 0 and 1 are the terminals. The language generated by this grammar is :
- (a){ 0n102n|n≥1}
- (b){0i10j10k |i,j,k≥0}∪{ 0n102n|n≥0}
- (c){0i10j |i,j≥0}∪{ 0n102n|n≥0}
- (d)The set of all strings over {0,1} containing at least two 0's
Match the following:
E. Checking that
identifiers are
declared before
their use
P. L={ anbmcndm |n≥1,m≥1}
F. Number of formal
parameters in the
declaration of a
function agrees with
the number of actual
parameters in a use of
that function
Q. X→XbX | XcX | dXf | g
G. Arithmetic
expressions with
matched pairs of
parentheses
R. L={wcw|w∈ (a+b)* }
H. Palindromes
S. X→bXb | cXc | ε- (a)E-P, F-R, G-Q, H-S.
- (b)E-R, F-P, G-S, H-Q
- (c)E-R, F-P, G-Q, H-S
- (d)E-P, F-R, G-S, H-Q
Consider the grammar given below: S → x B | yA A → x | xS | y A A B → y | yS | x B B Consider the following strings. i. xxyyx ii. xxyyxy iii. xyxy iv. yxxy v. yxx vi. xyx Which of the above strings are generated by the grammar?
- (a)i, ii and iii
- (b)ii, v and vi
- (c)ii, iii and iv
- (d)i, iii and iv
The two grammars given below generate a language over
the alphabet {x,y,z}
G1: S → x | z | xS | zS | yB
B → y | z | yB |zB
G2: S →y | z | yS | zS | xB
B →y | yS
Which one of the following choices describes the
properties satisfied by the strings in these languages?- (a)G1 : No y appears before any x G2 : Every x is followed by at least one y.
- (b)G1 : No y appears before any x G2 : No x appears before any y
- (c)G1 : No y appears after any x G2 : Every x is followed by at least one y
- (d)G1 : No y appears after any x G2 : Every y is followed by atleast one x
In the context-free grammar below, is the start symbol, and are terminals, and denotes the empty string. S →aSAb | ∈ A → bA | ∈ The grammar generates the language
- (a)((a+b)*b)
- (b)(ambn | m≤n )
- (c)(ambn | m=n )
- (d)a*b*
In the context-free grammar below,S is the start symbol,a and b are terminals, and ∈ denotes the empty string S →aSa | bSb | a | b | ∈ Which of the following strings is NOT generated by the grammar?
- (a)aaaa
- (b)baba
- (c)abba
- (d)babaaabab
Self-check
Question 1
Give a grammar for and the number of derivation steps for .
Show answerHide
; steps ( uses of the first production and of the second).
Question 2
Why is not a grammar for all palindromes?
Show answerHide
It generates only even-length palindromes: odd ones such as and need a single middle symbol ().
Question 3
A parse tree has how many leftmost derivations? How many derivations in all, for the tree of above?
Show answerHide
Exactly one leftmost derivation; derivations in all (the interleavings of the two chains).
Question 4
Is every regular language context-free? Show how for "ends with ".
Show answerHide
Yes: one variable per DFA state, and for accepting .
Revision card
One-screen revision
- ; derivations , ; ; parse tree, yield.
- One parse tree: one leftmost and one rightmost derivation, many others.
- Standard grammars: , palindromes, balanced, equal counts, union for or .
- Regular CFL. Beware (balanced, not equal counts).
References
- ·Sipser, Introduction to the Theory of Computation (3rd edition), Section 2.1 (context-free grammars)
- ·Hopcroft, Motwani, Ullman, Introduction to Automata Theory, Languages, and Computation (3rd edition), Chapter 5 (context-free grammars and languages)
- ·Aho, Lam, Sethi, Ullman, Compilers: Principles, Techniques, and Tools (2nd edition), Section 4.2 (context-free grammars)
Verification
scripts/enum-checks/toc_cfg.py: every grammar in the design table generates exactly the language of an independent predicate on all strings up to length 10 (over the alphabet of the language); the string counts per length were compared with the closed forms (1, 2^(n/2), 2^ceil(n/2), Catalan numbers, central binomial coefficients); the leftmost and rightmost derivation traces were replayed step by step and their trees read the string; the number of derivations of aabbb in all orders of expansion (10 = C(5, 2)) was found by exhaustive search; the right-linear grammar built from the DFA for 'ends with 01' generates that language on all strings up to length 10 and gives every string exactly one parse tree; the wrong grammar S -> aSb | SS | epsilon was shown to generate the balanced strings (with a as the opening symbol), not the strings with equal counts. Textbook chapter references are from memory. SECOND PASS (2026-11-02, done by the assistant, not a human check): every Self-check question was solved before the printed answer was read and all agreed; the definitions, worked examples, cheat box and traps were read claim by claim and the numbers re-derived by hand or by a small script (state counts, derivations, parse-tree and move counts, decomposition counts); tables and animations are machine output and were read, not re-run; No other defect found. Status raised to self-checked; verified needs a textbook or human check.
last verified: never
My notes (saved in this browser)