Which of the following grammars is/are ambiguous?
["B","C"]
Step-by-Step Solution
Key idea: This is a grammar ambiguity identification question. We need to check each grammar to see if any string has multiple distinct derivations.
Step 1: Check Grammar A: S → aSb | ε
This generates {a^n b^n | n ≥ 0}.
For any string a^n b^n, there's only ONE way to derive it:
- Must apply S → aSb exactly n times
- Then apply S → ε once
- Order is forced (always leftmost or always rightmost)
Grammar A is UNAMBIGUOUS.
Step 2: Check Grammar B: E → E+E | E*E | id
This is the classic expression grammar.
For string "id+id*id":
Derivation 1: E ⇒ E+E ⇒ id+E ⇒ id+EE ⇒ id+idE ⇒ id+idid (groups as id + (id id))
Derivation 2: E ⇒ EE ⇒ E+EE ⇒ id+EE ⇒ id+idE ⇒ id+idid (groups as (id + id) id)
Two different parse trees ⇒ Grammar B is AMBIGUOUS.
Step 3: Check Grammar C: S → aS | Sa | ε
For string "aa":
Derivation 1: S ⇒ aS ⇒ aaS ⇒ aa (using S → aS twice, then S → ε)
Derivation 2: S ⇒ Sa ⇒ aSa ⇒ aa (using S → Sa, then S → aS for the first S, then S → ε)
These are two distinct leftmost derivations for "aa".
Grammar C is AMBIGUOUS.
Step 4: Check Grammar D: S → aS | ε
This generates a* (any number of a's).
For string "aaa", there is only one leftmost derivation:
S ⇒ aS ⇒ aaS ⇒ aaaS ⇒ aaa
Grammar D is UNAMBIGUOUS.
Answer: Grammars B and C are ambiguous.