# Context-free grammar for language $L = \{u \in \{a, b\}^* \mid |u|_a = |u|_b\}$ [duplicate]

I need to find the production rules for the following language:

$$L = \{u \in \{a, b\}^* \mid |u|_a = |u|_b\}$$

Well, the first thing I could come up with is

$$S \to aSb | \epsilon$$

But this only covers the situation where all symbols $$a$$ precede $$b$$.So I tried to add all rules containing only one symbol of $$a$$, $$b$$, and one non-terminal symbol on the right-side:

$$S \to aSb|bSa|abS|baS|Sab|Sba|\epsilon$$

Do you think this would work?

I used this website CFG Developer and entered my productions, and for the string "bbbbaaaaabababbabababbaa" the output is false, meaning that the string cannot be produced by the mentioned rules.

Does anyone know where the mistake is?

• Has been asked and answered several times on this site. May 30, 2022 at 9:18
• The correct grammar $S\to SS\mid 0S1\mid 1S0\mid \varepsilon$ is analysed by John L. in How to construct Context Free Grammar of words with equal number of 0's and 1's. A different approach (which can be connected to the pushdown automaton) $S\to aB\mid bA$, $A\to a\mid aS\mid bAA$, $B→b\mid bS\mid aBB$ is discussed in Is my proof for a context free language correct? Same number of a's as b's May 30, 2022 at 11:12
• @johndoe Your grammar does not generate word $aabbbbaa$, because of $aa$ both at the start and at the end. As mentioned in my answer to another question, there must be a production rule that contains two $S$s. May 30, 2022 at 18:08

By your above mentioned grammar $$S \to aSb|bSa|abS|baS|Sab|Sba|\epsilon$$ has four redundants $$abS,baS,Sab,Sba$$ and one missing term is $$SS.$$ Because if you use $$S \to aSb|bSa|\epsilon$$ only after removing redundants then the strings that does starts and ends with same symbol like $$abba$$ is not possible to generate(but $$n_a(w)=n_b(w)$$), that's why you need to add $$SS.$$
Therefore your complete grammar is $$S \to aSb|bSa|SS|\epsilon$$