Ambiguity in grammars
Ambiguity of context-free grammars: a grammar is ambiguous when some string has two parse trees (equivalently two leftmost or two rightmost derivations), counting parse trees by dynamic programming, the Catalan explosion for bracketing grammars, cyclic grammars with infinitely many trees, removing ambiguity by layering (precedence and associativity), unambiguous grammars for the standard languages, inherently ambiguous languages, and undecidability of ambiguity.
Why it exists
A grammar is supposed to give each string a meaning, through its parse tree. If one string has two trees it has two meanings, and a compiler would not know which to use. GATE asks: is this grammar ambiguous, find two parse trees, count the parse trees, remove the ambiguity, which languages are inherently ambiguous. The compiler side of ambiguity (dangling else, operator precedence) is on grammar ambiguity in compilers; this page is the theory.
Prerequisites
You need grammars, derivations and parse trees (context-free grammars).
Precise definitions
A CFG is ambiguous if some string has two different parse trees. These conditions are equivalent:
- has two different parse trees;
- has two different leftmost derivations;
- has two different rightmost derivations.
(Two different derivations are not enough, since different orders of expansion give different derivations of the same tree.) A grammar that is not ambiguous is unambiguous.
A language is inherently ambiguous if every grammar for it is ambiguous. Ambiguity belongs to grammars; inherent ambiguity belongs to languages.
If a grammar has a variable with (a cycle of unit productions or of nullable symbols around ) that is used in the derivation of some string, that string has infinitely many parse trees, so the grammar is ambiguous.
How it works
Finding and counting parse trees
For a string , let be the number of parse trees with root and yield . Then is computed from shorter substrings: for each production sum, over all ways to split the substring into consecutive parts, the product of the counts for the parts (a terminal contributes if it equals the symbol). The number of parse trees of is . This is the same table as in the CYK algorithm, with counts instead of yes/no.
Example: .
First leftmost derivation of aaa (the left S S is split first): 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 → a
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.
Second leftmost derivation of aaa (the right S S is split first): 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 → a
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.
The string has two parse trees: and , found as two different leftmost derivations.
The Catalan explosion
For a binary operator without precedence rules, each string with operators has one tree for each way to bracket it, and that number is the Catalan number : . The layered grammar , (left associative) has exactly one tree.
Parse trees of id + id + ... + id: start
Computed by a script, not typed| operators | E → E + E | id | E → E + T | T, T → id | E → E + E | E * E | id (alternating + and *) |
|---|---|---|---|
| 0 operators | |||
| 1 operators | |||
| 2 operators | |||
| 3 operators | |||
| 4 operators | |||
| 5 operators | |||
| 6 operators | |||
| 7 operators |
Step 0
Counting parse trees by dynamic programming over the substrings of the input. More than one tree means the string has several leftmost derivations: the grammar is ambiguous.
(The first column is , the second the layered grammar, the third on a string whose operators alternate and : with no precedence there are again trees.)
Removing ambiguity
- Precedence by layering. Give each precedence level its own variable: , , . Operators lower in the layers bind tighter.
- Associativity by the shape of the recursion. (recursion on the left) makes left associative; makes it right associative.
- Dangling else: match each
elsewith the nearest unmatchedthenby separating matched and unmatched statements (see the compiler page).
Unambiguous grammars (checked: at most one parse tree for every string up to length ):
| language | an unambiguous grammar |
|---|---|
| palindromes | |
| balanced parentheses | |
| , | , |
| , | , , |
| equal numbers of and | , , |
Here generates the strings with exactly one more than and in which no proper prefix has that property, the mirror image.
Typical ambiguous grammars: (the string has trees), for , the equal-count grammar ( has two trees), and anything with together with other ways to make the same string.
Cyclic grammars
For the derivation can be inserted any number of times (using for one of the 's): every string, even , has infinitely many parse trees. The same holds for (a unit cycle) and for . A computation that counts trees reports "infinitely many".
Inherent ambiguity
The language has the natural grammar with , , , . It is ambiguous exactly on the strings with : those can be generated by the left part and by the right part. It is a textbook theorem (quoted, not proved here) that every grammar for is ambiguous, so is inherently ambiguous.
S → X C | A Y for a^i b^j c^k with i = j or j = k: start
Computed by a script, not typed| string | parse trees | in the language |
|---|---|---|
| ε | ||
| abc | ||
| aabbcc | ||
| aabbc | ||
| abbcc | ||
| aabbbcc | ||
| aabcc | ||
| aaabbbccc | ||
| abb |
Step 0
The natural grammar for 'i = j or j = k' is ambiguous exactly on the strings a^n b^n c^n. It is a standard result (quoted, not proved here) that EVERY grammar for this language is ambiguous: the language is inherently ambiguous.
Deciding ambiguity
There is no algorithm that decides whether an arbitrary grammar is ambiguous (the problem is undecidable; textbook theorem, quoted). One can only test strings up to a bound, as the tables here do, or prove unambiguity for special classes: every LL(1) and every LR(k) grammar is unambiguous (textbook fact, quoted; LL(1) parsing).
Worked examples
EX 1Show ambiguity
Easyis ambiguous: has one tree with at the root and another with at the root. Two leftmost derivations, differing in the first step, prove it.
EX 2Count the parse trees
EasyHow many parse trees does have under ? Three operators: . Under , : .
EX 3A grammar that looks unambiguous
Mediumgenerates . The string has two leftmost derivations: and . So the grammar is ambiguous, even though the language is not (use , ).
EX 4Is the language inherently ambiguous
MediumLanguages that need two "overlapping" comparisons, such as , are the textbook examples of inherently ambiguous languages. A language like is not: it has an unambiguous grammar. To show a language is not inherently ambiguous, exhibit an unambiguous grammar; to show it is, a long proof is needed (not asked in GATE beyond recognising the standard example).
EX 5Typical questions
GATE level(a) "A grammar is ambiguous iff some string has two derivation trees / two leftmost derivations / two rightmost derivations." True; "two derivations" alone is not enough. (b) "Every regular language has an unambiguous grammar." True (the right-linear grammar of a DFA). (c) "Unambiguity is decidable." False. (d) "Number of parse trees of under :" three operators: . (e) "Is ambiguous?" Yes: has trees, has .
Cheat box
Cheat box
- Ambiguous: some string with two parse trees = two leftmost = two rightmost derivations.
- Bracketing grammars: Catalan numbers for operators.
- Remove ambiguity: layer by precedence, make recursion left for left associativity.
- Inherently ambiguous language: . Ambiguity of grammars is undecidable.
- Cyclic () grammars: infinitely many trees.
Traps and GATE patterns
Connections
Across subjects
Compilers need unambiguous grammars (or precedence declarations) to give a program one meaning (ambiguity in compilers); every deterministic context-free language has an unambiguous grammar (textbook theorem, quoted; deterministic versus nondeterministic PDA); the grammar-to-PDA construction keeps the derivation structure (PDA and CFG).
PYQs
2 previous year questions from your book. I re-solved each one myself (2 by running or simulating, 0 by reasoning only); the book's key is shown next to my answer. All PYQs
Consider the following grammar where S is the start symbol, and a and b are terminal symbols. S→aSbS | bS | ε Which of the following statements is/are true?
- (a)The grammar is ambiguous
- (b)The string abb has two distinct derivations in this grammar
- (c)The string abab has only one rightmost derivation
- (d)The language generated by the grammar is undecidable
Which of the following grammars is/are ambiguous?
- (a). S → aSb | ε
- (b). E → E + E | E * E | id
- (c). S → aS | Sa | ε
- (d). S → aS | ε
Self-check
Question 1
How many parse trees does have under ?
Show answerHide
Four operators: .
Question 2
Is ambiguous? What language does it generate and what is an unambiguous grammar for it?
Show answerHide
Yes ( has two trees; has ). The language is ; is unambiguous.
Question 3
True or false: if a string has two different derivations, the grammar is ambiguous.
Show answerHide
False. It must have two different parse trees (two leftmost derivations).
Question 4
Name an inherently ambiguous language.
Show answerHide
.
Revision card
One-screen revision
- Ambiguous = a string with two parse trees (two leftmost derivations).
- Catalan numbers count bracketings; layering by precedence and left recursion for left associativity remove ambiguity.
- Inherently ambiguous: or . Ambiguity is undecidable.
- Cyclic grammars have infinitely many trees.
References
- ·Sipser, Introduction to the Theory of Computation (3rd edition), Section 2.1 (ambiguity)
- ·Hopcroft, Motwani, Ullman, Introduction to Automata Theory, Languages, and Computation (3rd edition), Section 5.4 (ambiguity in grammars and languages)
- ·Aho, Lam, Sethi, Ullman, Compilers: Principles, Techniques, and Tools (2nd edition), Section 4.3.2 (ambiguity, dangling else)
Verification
scripts/enum-checks/toc_cfg.py: parse trees are counted by a memoised span count and compared with the number of leftmost derivations and the number of rightmost derivations found by exhaustive search (120 random grammars, all strings up to length 6); for S -> SS | a and E -> E + E | id the counts are the Catalan numbers up to n = 8 operators and for the layered grammar 1; nine grammars on this page (palindromes, balanced parentheses, a^n b^n, a^i b^j, i != j, i >= j in two forms, a^n b^2n, equal counts in the unambiguous form, the layered expression grammar) have at most one parse tree for every string up to length 10; the ambiguous forms (S -> aS | Sa | a with 2^(n-1) trees, the equal-count grammar with 2 trees for abab, the i >= j grammar with several trees for aab) were counted; the cyclic grammars raise 'infinitely many trees'; the grammar for i = j or j = k has 2 trees exactly for the strings with i = j = k. The inherent ambiguity of that language, the facts that LL(1) and LR(k) grammars are unambiguous and that deterministic context-free languages have unambiguous grammars, and the undecidability of ambiguity are textbook theorems, quoted and NOT machine-proved here (needs verification). 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)