Consider the following two context-free grammars G1 and G2: G1 G2 S → XY S →…
Consider the following two context-free grammars G1 and G2:
G1 G2
S → XY S → PQ | aaR
X → aX|U P → aP | M
Y → Yb|Yc|Ybc|Vc Q → Qc | N
U → aZ | ε M → aR | ε
V → Zbb N → Rc | ε
Z → Y|b|ε R → aP|b
Which of the following is correct?
Answer: C. Both G1 and G2 are ambiguous. — Answer: Both grammars are ambiguous. Reason and example for the first grammar (G1): Consider the string "abbc". We show two distinct leftmost derivations that…
- A.
Only G1 is ambiguous.
- B.
Only G2 is ambiguous.
- C.
Both G1 and G2 are ambiguous.
- D.
Neither G1 nor G2 is ambiguous.
Attempted by 11 students.
Show answer & explanation
Correct answer: C
Answer: Both grammars are ambiguous.
Reason and example for the first grammar (G1):
Consider the string "abbc". We show two distinct leftmost derivations that produce this string.
Derivation 1 (X produces the prefix "a" by using X → aX and then U → ε):
S → X Y
X → aX → aU → aε (so X ⇒ a)
Y → V c, V → Z b b, Z → ε (so Y ⇒ b b c)
Combined: S ⇒ X Y ⇒ a (bbc) = abbc
Derivation 2 (X produces the prefix "a" by using U → aZ and Z → ε):
S → X Y
X → U → aZ → aε (so X ⇒ a by a different sequence)
Y → V c, V → Z b b, Z → ε (so Y ⇒ b b c as before)
Combined: S ⇒ X Y ⇒ a (bbc) = abbc
Because there are two different parse trees (different production choices inside X) that yield the same terminal string, the first grammar is ambiguous.
Reason and example for the second grammar (G2):
Consider the string "aab".
Derivation 1 (use S → aaR):
S → aaR, R → b ⇒ a a b = aab
Derivation 2 (use S → P Q with Q ⇒ ε and P producing the same prefix):
Choose P → aP → M, M → aR, and then R → b, so P ⇒ a a b
Choose Q → N → ε, so Q ⇒ ε. Combined: S ⇒ P Q ⇒ (aab) ε = aab
These are two different parse trees for the same string, so the second grammar is ambiguous.
Conclusion: Both grammars are ambiguous because each admits at least one terminal string with two distinct parse trees (examples and derivations shown above).
A video solution is available for this question — log in and enroll to watch it.