Consider the following grammars:

Grammar 1: <s> ::= a <s> | b <s> | ε
Grammar 2: <s> ::= a | b | <s> <s> | ε
Grammar 3: <s> ::= a <s> b | ε
Grammar 4: <s> ::= <s> a | <s> b | a
Grammar 5: <s> ::= a <r> | <r>
<r> ::= b <s> | <s> | ε

How many of these grammars are ambiguous?

2
  1. 0
  2. 1
  3. 2
  4. 3
  5. 4
  6. 5

Review the definition of an ambiguous grammar.

For each grammar, when looking for strings with multiple parse trees, start with the shortest strings that the grammar generates.

Common sources of grammatical ambiguity include recursive patterns such as double recursion and single, indirect recursion (i.e., from one non-terminal back to itself via one or more other non-terminals).

Grammar 1 is not ambiguous because every string in its language is either empty or starts with an a or a b. This grammar handles each case once and generates each string in only one way, namely from left to right.

Grammar 2 is ambiguous because of the double recursion in its third production. For example, the strings ε and a have more than one parse tree.

Grammar 3 is not ambiguous because the only production that can produce a non-empty string is the first one.

Grammar 4 is not ambiguous because every string in its language is either empty or ends with an a or a b. This grammar handles each case once and generates each string in only one way, namely from right to left.

Grammar 5 is ambiguous because, for example, <s> can generate <r>, which in turn can re-generate <s>, leading to infinitely many, arbitrarily deep parse trees for all strings, including ε.