Context-Free Grammars & Languages

Answer & solution
Official answer: B, C
Givens and goal
Which grammars are ambiguous? A S→aSb|ε; B E→E+E|E*E|id; C S→aS|Sa|ε; D S→aS|ε.
Approach
Exhibit two parse trees for ambiguous choices and explain uniqueness for the others.
Step-by-step solution
1. B generates id+id*id with root production E→E+E, whose right child expands by multiplication. It also generates the same string with root E→E*E, whose left child expands by addition. These are different tree structures, corresponding to id+(id*id) and (id+id)*id.
2. C already has two trees for the one-letter string a: use S→aS→aε, or S→Sa→εa. The root productions differ, so this is genuine ambiguity, not merely a different order of expanding independent nodes.
3. For A, every nonempty string is aⁿbⁿ. The first rule must be aSb and must be applied exactly n times, followed by ε. No alternative tree is possible for that n.
4. For D, a string aⁿ requires exactly n applications of aS followed by ε. Again the chain is unique.
5. Therefore B,C are ambiguous. The existence of an unambiguous grammar for the same language would not remove ambiguity from these particular grammars.