Given the following two grammars : G1 : S → AB | aaB A → a | Aa B → b G2 : S →…
2014
Given the following two grammars :
G1 : S → AB | aaB
A → a | Aa
B → b
G2 : S → a S b S | b S a S | λ
Which statement is correct ?
- A.
G1 is unambiguous and G2 is unambiguous.
- B.
G1 is unambiguous and G2 is ambiguous.
- C.
G1 is ambiguous and G2 is unambiguous.
- D.
G1 is ambiguous and G2 is ambiguous.
Attempted by 124 students.
Show answer & explanation
Correct answer: D
Answer: Both grammars are ambiguous.
Proof for the first grammar (G1):
Consider the string "aab".
Derivation 1 (using S → AB): S ⇒ AB ⇒ AaB ⇒ aaB ⇒ aab
Derivation 2 (using S → aaB): S ⇒ aaB ⇒ aab
Since there are two distinct derivations for the same string, G1 is ambiguous.
Proof for the second grammar (G2):
Consider the string "abab".
Derivation 1 (root expands with a S b S, left S → λ, right S → a S b S with both inner S → λ):
S ⇒ a S b S ⇒ a (λ) b (a S b S) ⇒ a b a b
Derivation 2 (root expands with a S b S, left S ⇒ b S a S with both inner S ⇒ λ, right S ⇒ λ):
S ⇒ a S b S ⇒ a (b S a S) b S ⇒ a (b λ a λ) b λ ⇒ a b a b
These are two different parse trees/derivations yielding the same string, so G2 is ambiguous.
Conclusion: Both grammars are ambiguous because we have exhibited specific strings with two distinct derivations in each grammar.