G27
Self-checkedTier 1 9 min readtoc.cfg-ambiguity

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 GG is ambiguous if some string w∈L(G)w \in L(G) has two different parse trees. These conditions are equivalent:

  • ww has two different parse trees;
  • ww has two different leftmost derivations;
  • ww 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 AA with A⇒+AA \Rightarrow^+ A (a cycle of unit productions or of nullable symbols around AA) 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 w=w1⋯wnw = w_1 \cdots w_n, let c(A,i,j)c(A, i, j) be the number of parse trees with root AA and yield wi⋯wjw_i \cdots w_j. Then cc is computed from shorter substrings: for each production A→X1⋯XkA \to X_1 \cdots X_k sum, over all ways to split the substring into kk consecutive parts, the product of the counts for the parts (a terminal contributes 11 if it equals the symbol). The number of parse trees of ww is c(S,1,n)c(S, 1, n). This is the same table as in the CYK algorithm, with counts instead of yes/no.

Example: S→SS∣aS \to S S \mid a.

First leftmost derivation of aaa (the left S S is split first): start

Parser run by a script, not typed

Leftmost derivation (the sentential form is on the left; the string to derive is on the right).

  1. 1S → S S
  2. 2S → a
sentential form
S
string to derive
aaa
action start
parse tree so far
S

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.

0 / 5
computed by script: the machine is simulated or the sets are constructed by scripts/toc_lib.py, one step at a time. python3 scripts/gen-toc3-traces.py

Second leftmost derivation of aaa (the right S S is split first): start

Parser run by a script, not typed

Leftmost derivation (the sentential form is on the left; the string to derive is on the right).

  1. 1S → S S
  2. 2S → a
sentential form
S
string to derive
aaa
action start
parse tree so far
S

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.

0 / 5
computed by script: the machine is simulated or the sets are constructed by scripts/toc_lib.py, one step at a time. python3 scripts/gen-toc3-traces.py

The string aaaaaa has two parse trees: (aa)a(aa)a and a(aa)a(aa), found as two different leftmost derivations.

The Catalan explosion

For a binary operator without precedence rules, each string id+id+⋯\mathrm{id} + \mathrm{id} + \cdots with nn operators has one tree for each way to bracket it, and that number is the Catalan number Cn=1n+1(2nn)C_n = \frac{1}{n + 1} \binom{2n}{n}: 1,1,2,5,14,42,132,4291, 1, 2, 5, 14, 42, 132, 429. The layered grammar E→E+T∣TE \to E + T \mid T, T→idT \to \mathrm{id} (left associative) has exactly one tree.

Parse trees of id + id + ... + id: start

Computed by a script, not typed
operatorsE → E + E | idE → E + T | T, T → idE → 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.

0 / 8
computed by script: the machine is simulated or the sets are constructed by scripts/toc_lib.py, one step at a time. python3 scripts/gen-toc3-traces.py

(The first column is E→E+E∣idE \to E + E \mid \mathrm{id}, the second the layered grammar, the third E→E+E∣E∗E∣idE \to E + E \mid E * E \mid \mathrm{id} on a string whose operators alternate ++ and ∗*: with no precedence there are again CnC_n trees.)

Removing ambiguity

  1. Precedence by layering. Give each precedence level its own variable: E→E+T∣TE \to E + T \mid T, T→T∗F∣FT \to T * F \mid F, F→(E)∣idF \to (E) \mid \mathrm{id}. Operators lower in the layers bind tighter.
  2. Associativity by the shape of the recursion. E→E+TE \to E + T (recursion on the left) makes ++ left associative; E→T+EE \to T + E makes it right associative.
  3. Dangling else: match each else with the nearest unmatched then by separating matched and unmatched statements (see the compiler page).

Unambiguous grammars (checked: at most one parse tree for every string up to length 1010):

languagean unambiguous grammar
anbna^n b^nS→aSb∣εS \to aSb \mid \varepsilon
palindromesS→aSa∣bSb∣a∣b∣εS \to aSa \mid bSb \mid a \mid b \mid \varepsilon
balanced parenthesesS→( S ) S∣εS \to (\,S\,)\,S \mid \varepsilon
aibja^i b^j, i≥ji \ge jS→aS∣TS \to aS \mid T, T→aTb∣εT \to aTb \mid \varepsilon
aibja^i b^j, i≠ji \ne jS→aSb∣A∣BS \to aSb \mid A \mid B, A→aA∣aA \to aA \mid a, B→bB∣bB \to bB \mid b
equal numbers of aa and bbS→aBS∣bAS∣εS \to aBS \mid bAS \mid \varepsilon, A→a∣bAAA \to a \mid bAA, B→b∣aBBB \to b \mid aBB

Here AA generates the strings with exactly one more aa than bb and in which no proper prefix has that property, BB the mirror image.

Typical ambiguous grammars: S→aS∣Sa∣aS \to aS \mid Sa \mid a (the string ana^n has 2n−12^{n-1} trees), S→aSb∣aS∣εS \to aSb \mid aS \mid \varepsilon for i≥ji \ge j, the equal-count grammar S→aSbS∣bSaS∣εS \to aSbS \mid bSaS \mid \varepsilon (abababab has two trees), and anything with S→SSS \to SS together with other ways to make the same string.

Cyclic grammars

For S→SS∣(S)∣εS \to SS \mid (S) \mid \varepsilon the derivation S⇒SS⇒S⇒SS⇒⋯S \Rightarrow SS \Rightarrow S \Rightarrow SS \Rightarrow \cdots can be inserted any number of times (using S→εS \to \varepsilon for one of the SS's): every string, even ε\varepsilon, has infinitely many parse trees. The same holds for S→S∣aS \to S \mid a (a unit cycle) and for S→aSb∣SS∣εS \to aSb \mid SS \mid \varepsilon. A computation that counts trees reports "infinitely many".

Inherent ambiguity

The language L={aibjck:i=j or j=k}L = \{a^i b^j c^k : i = j \text{ or } j = k\} has the natural grammar S→XC∣AYS \to XC \mid AY with X→aXb∣εX \to aXb \mid \varepsilon, C→cC∣εC \to cC \mid \varepsilon, A→aA∣εA \to aA \mid \varepsilon, Y→bYc∣εY \to bYc \mid \varepsilon. It is ambiguous exactly on the strings with i=j=ki = j = k: 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 LL is ambiguous, so LL 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
stringparse treesin 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.

0 / 9
computed by script: the machine is simulated or the sets are constructed by scripts/toc_lib.py, one step at a time. python3 scripts/gen-toc3-traces.py

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

Easy

E→E+E∣E∗E∣idE \to E + E \mid E * E \mid \mathrm{id} is ambiguous: id+id∗id\mathrm{id} + \mathrm{id} * \mathrm{id} 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

Easy

How many parse trees does id+id+id+id\mathrm{id} + \mathrm{id} + \mathrm{id} + \mathrm{id} have under E→E+E∣idE \to E + E \mid \mathrm{id}? Three operators: C3=5C_3 = 5. Under E→E+T∣TE \to E + T \mid T, T→idT \to \mathrm{id}: 11.

EX 3A grammar that looks unambiguous

Medium

S→aSb∣aS∣εS \to a S b \mid a S \mid \varepsilon generates {aibj:i≥j}\{a^i b^j : i \ge j\}. The string aabaab has two leftmost derivations: S⇒aSb⇒aaSb⇒aabS \Rightarrow aSb \Rightarrow aaS b \Rightarrow aab and S⇒aS⇒aaSb⇒aabS \Rightarrow aS \Rightarrow aaSb \Rightarrow aab. So the grammar is ambiguous, even though the language is not (use S→aS∣TS \to aS \mid T, T→aTb∣εT \to aTb \mid \varepsilon).

EX 4Is the language inherently ambiguous

Medium

Languages that need two "overlapping" comparisons, such as {aibjck:i=j or j=k}\{a^i b^j c^k : i = j \text{ or } j = k\}, are the textbook examples of inherently ambiguous languages. A language like {aibj:i≥j}\{a^i b^j : i \ge j\} 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 id+id∗id+id\mathrm{id} + \mathrm{id} * \mathrm{id} + \mathrm{id} under E→E+E∣E∗E∣idE \to E + E \mid E * E \mid \mathrm{id}:" three operators: C3=5C_3 = 5. (e) "Is S→SS∣aS \to SS \mid a ambiguous?" Yes: aaaaaa has 22 trees, ana^n has Cn−1C_{n - 1}.

Cheat box

Cheat box

  • Ambiguous: some string with two parse trees = two leftmost = two rightmost derivations.
  • Bracketing grammars: Catalan numbers 1,1,2,5,14,42,132,4291, 1, 2, 5, 14, 42, 132, 429 for 0,1,2,…0, 1, 2, \ldots operators.
  • Remove ambiguity: layer by precedence, make recursion left for left associativity.
  • Inherently ambiguous language: {aibjck:i=j or j=k}\{a^i b^j c^k : i = j \text{ or } j = k\}. Ambiguity of grammars is undecidable.
  • Cyclic (A⇒+AA \Rightarrow^+ A) grammars: infinitely many trees.

Traps and GATE patterns

Connections

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

GATE 2026 · Set 1 · MSQ · 1 markQ1 · page 225 of the book
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
GATE 2026 · Set 2 · MSQ · 1 markQ2 · page 225 of the book
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 id+id+id+id+id\mathrm{id} + \mathrm{id} + \mathrm{id} + \mathrm{id} + \mathrm{id} have under E→E+E∣idE \to E + E \mid \mathrm{id}?

Show answer

Four operators: C4=14C_4 = 14.

Question 2

Is S→aS∣Sa∣aS \to aS \mid Sa \mid a ambiguous? What language does it generate and what is an unambiguous grammar for it?

Show answer

Yes (aaaa has two trees; ana^n has 2n−12^{n - 1}). The language is a+a^+; S→aS∣aS \to aS \mid a is unambiguous.

Question 3

True or false: if a string has two different derivations, the grammar is ambiguous.

Show answer

False. It must have two different parse trees (two leftmost derivations).

Question 4

Name an inherently ambiguous language.

Show answer

{aibjck:i=j or j=k}\{a^i b^j c^k : i = j \text{ or } j = k\}.

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: i=ji = j or j=kj = k. 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