I am stuck and having a hard time with this question. I want to construct a CFG for the language $$L = \{{a^lb^mc^n | l,m\in N, n=|l-m|\}}$$ I know that the language consists of strings where:
1. number of a's = number of b's, so c=0
2. number of a's more than number of b's, c=l-m
3. number of a's less than number of b's, c=-(l-m)
I started with $$S->ab$$ $$S->aSb$$ This generates all of case one, where number of a's = number of b's and c=0. I know that I could increment a's and c's by having aSc but I cant put that in the second line because it could generate a(aSc)b which is not in the language.


marked as duplicate by Hendrik Jan, Karolis Juodelė, AProgrammer, D.W., Raphael Nov 3 '13 at 22:53

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


Hint: try to do each language separately, and then your final grammar is S->S1|S2|S3.

To do your case 2, you can write



I.e. you start by generating the c's and the exceeding a's, and then you generate the b's and the remaining a.

  • $\begingroup$ Note that we usually try and not enable people who try and have their homework done for them. $\endgroup$ – Raphael Nov 3 '13 at 22:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.