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…

  1. A.

    Only G1 is ambiguous.

  2. B.

    Only G2 is ambiguous.

  3. C.

    Both G1 and G2 are ambiguous.

  4. 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):

  1. Consider the string "abbc". We show two distinct leftmost derivations that produce this string.

  2. 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

  3. 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

  4. 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):

  1. Consider the string "aab".

  2. Derivation 1 (use S → aaR):

    S → aaR, R → b ⇒ a a b = aab

  3. 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

  4. 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.

Explore the full course: Gate Guidance By Sanchit Sir

Loading lesson…