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,724
  • 2
  • 29
  • 49
am2021
  • 67
  • 3

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,724
  • 2
  • 29
  • 49