Question:

Which of the following grammars is/are ambiguous?

Show Hint

Look for a string with more than one distinct parse tree; grammar B (no operator precedence between + and *) and grammar C (mixed left and right recursion on the same symbol) both admit this, while A and D generate every string uniquely.
Updated On: Aug 4, 2026
  • π‘†β†’π‘Žπ‘†π‘ | πœ–
  • 𝐸→𝐸+ 𝐸 | πΈβˆ—πΈ | 𝑖𝑑
  • π‘†β†’π‘Žπ‘† | π‘†π‘Ž | πœ–
  • π‘†β†’π‘Žπ‘† | πœ–
Show Solution
collegedunia
Verified By Collegedunia

The Correct Option is B, C

Solution and Explanation

A grammar is ambiguous if some string in its language has two or more distinct parse trees (equivalently, two distinct leftmost derivations).

Step 1: Check Option A - \(S \to aSb \mid \epsilon\). This generates \(\{a^n b^n \mid n \ge 0\}\). Every string has exactly one derivation, since at each step there is only one way to expand \(S\) (terminate with \(\epsilon\), or wrap another \(a \ldots b\) pair). Unambiguous.

Step 2: Check Option B - \(E \to E+E \mid E*E \mid id\). Consider the string \(id + id * id\). It can be parsed as \((id + id) * id\) (applying \(+\) first) or as \(id + (id * id)\) (applying \(*\) first). Since the grammar defines no precedence or associativity, both are valid derivations, giving two distinct parse trees for the same string. Ambiguous.

Step 3: Check Option C - \(S \to aS \mid Sa \mid \epsilon\). This generates \(\{a^n \mid n \ge 0\}\), but because both left recursion (\(Sa\)) and right recursion (\(aS\)) are available simultaneously, a string like \(aa\) can be built in more than one structurally distinct way (attaching the two symbols in different orders via \(aS\) versus \(Sa\)), producing multiple parse trees for the same string. Ambiguous.

Step 4: Check Option D - \(S \to aS \mid \epsilon\). A simple right-linear grammar generating \(\{a^n \mid n \ge 0\}\), with only one production choice at each step. Every string has a unique derivation. Unambiguous.

Final Answer: \(\boxed{\text{Options B and C are ambiguous}}\)

Was this answer helpful?
0
0

Top GATE CS Computer Science and IT Engineering Questions

View More Questions

Top GATE CS Context Free Languages and Pushdown Automata Questions