1

I am learning automata theory, and I am confused about this exercise:

Give context free grammar to create the following language where the input alphabet is $\{a,b\}$

$L = \{w \text{ where }w\text{ is NOT of the form }b^n a^n\}$

So, I understand how to create $\{b^n a^n, n\in\mathbb{N}\}$:

$$S \to bSa \mid \epsilon$$

But I am lost as to how to generate a language that is $\{w \text{ where }w\text{ is NOT of the form }b^n a^n\}$. Help would be appreciated.

Steven
  • 29,419
  • 2
  • 28
  • 49
am2021
  • 67
  • 3
  • 2
    You are asking for the complement of the context-free language ${b^na^n\mid n\ge 0 }$. In this case this complement is also context-free (see the answer). Note however that in general the complement of a context-free language is not itself context-free. – Hendrik Jan Mar 31 '21 at 17:32

1 Answers1

4

A word in $L$ must either be of the form $b^i a^j$ with $i \neq j$ or it must have $ab$ as a substring. Therefore you can write a context-free grammar $G$ for $L$ as the union of two context-free grammars $G_1$ and $G_2$ for $L_1 = \{b^i a^j \mid i \neq j\}$ and $L_2 = \{w \in \{a,b\}^* \mid ab \mbox{ is a substring of } w\}$.

It is easy to come up with a context-free grammar $G_2$. In fact, it is even easy to come up with a regular expression for $L_2$: $(a \mid b)^*ab(a \mid b)^*$. Therefore I will only focus building $G_1$.

A word in $w=b^ia^j \in L_1$ can be written as $w = b^k \alpha a^k$, where $k = \min \{i,j \}$ and $\alpha$ is a non-empty string containing only $a$s or only $b$s. Conversely, all words of the form $b^k \alpha a^k$ belong to $L_1$. Then, this is a valid grammar $G_1$:

$$ \begin{align*} S &\to bSa \mid A \mid B \\ A & \to aA \mid a \\ B & \to bB \mid b \end{align*} $$

Steven
  • 29,419
  • 2
  • 28
  • 49
  • Thank you! If I wanted to create a push-down automata for this language, what would it look like? – am2021 Apr 01 '21 at 02:49
  • I created a separate question for this here (If you find the time to answer it, I'd be grateful): https://cs.stackexchange.com/questions/138369/how-do-you-design-a-push-down-automata-for-this-cfl – am2021 Apr 01 '21 at 02:59
  • There are automated ways to transform a grammar into a PDA. – Steven Apr 01 '21 at 09:36