Context-Free Grammars & Languages

Answer & solution
Official answer: D
Step through it (4 derivations)
1. Use the invariant #a−#b≥0. ε starts at zero; SaS increases it by one; aSb and bSa preserve it; SS adds two nonnegative differences. All generated strings satisfy the invariant.
2. babba has two a’s and three b’s, violating it, so D cannot be generated. To ensure it is the only excluded option, exhibit constructions for the others.
3. For abab, use S⇒SS⇒aSb aSb⇒abab. For aaab, use S⇒aSb⇒aSaSb⇒aaSb⇒aaSaSb⇒aaaSb⇒aaab. For abbaa, concatenate ab,ba,a using SS, using S⇒aSb⇒ab, S⇒bSa⇒ba, and S⇒SaS⇒a (ε reductions are implicit). Thus A,B,C are generated.