# Ambiguity in Grammar

A grammar is said to be ambiguous if there exists more than one leftmost derivation or more than one rightmost derivation or more than one parse tree for the given input string. If the grammar is not ambiguous, then it is called unambiguous.

If the grammar has ambiguity, then it is not good for compiler construction. No method can automatically detect and remove the ambiguity, but we can remove ambiguity by re-writing the whole grammar without ambiguity.

### Example 1:

Let us consider a grammar G with the production rule

**Solution:**

For the string “3 * 2 + 5”, the above grammar can generate two parse trees by leftmost derivation:

Since there are two parse trees for a single string “3 * 2 + 5”, the grammar G is ambiguous.

### Example 2:

Check whether the given grammar G is ambiguous or not.

**Solution:**

From the above grammar String “id + id – id” can be derived in 2 ways:

**First Leftmost derivation**

**Second Leftmost derivation**

Since there are two leftmost derivation for a single string “id + id – id”, the grammar G is ambiguous.

### Example 3:

Check whether the given grammar G is ambiguous or not.

**Solution:**

For the string “aabb” the above grammar can generate two parse trees

Since there are two parse trees for a single string “aabb”, the grammar G is ambiguous.

### Example 4:

Check whether the given grammar G is ambiguous or not.

**Solution:**

For the string “a(a)aa” the above grammar can generate two parse trees:

Since there are two parse trees for a single string “a(a)aa”, the grammar G is ambiguous.