The context free grammar for the language L = {an bm | n ≤ m + 3, n ≥ 0, m ≥…
2013
The context free grammar for the language
L = {an bm | n ≤ m + 3, n ≥ 0, m ≥ 0} is
- A.
S → aaa A; A → aAb | B, B → Bb | λ
- B.
S → aaaA|λ, A → aAb | B, B → Bb | λ
- C.
S → aaaA | aa A | λ, A → aAb | B, B → Bb| λ
- D.
S → aaaA | aa A | aA | λ, A → aAb | B, B → Bb | λ
Attempted by 29 students.
Show answer & explanation
Correct answer: D
Correct grammar: S → λ | aA | aaA | aaaA; A → aAb | B; B → Bb | λ
Why this works:
For any given n and m with n ≤ m + 3 let k = min(n,m) and p = n − k (so 0 ≤ p ≤ 3).
Use S → a^p A to produce the p unmatched leading a's (p is at most 3).
Apply A → aAb exactly k times to produce a^k B b^k (these create k matched a/b pairs).
Finally use B → Bb repeatedly (m − k times) to add the remaining b's, yielding a^{p+k} b^m = a^n b^m.
Conversely, any string derived from the grammar has at most three unmatched leading a's (provided by S), any further a's are paired with b's via A, and B only adds extra b's. Hence any derived string satisfies n − m ≤ 3, i.e. n ≤ m + 3.
Why the other given grammars fail:
A grammar that forces exactly three leading a's (for example S → aaaA with no productions for fewer a's) cannot generate strings like 'a' or 'aa' or the empty string when those should be in the language.
A grammar that omits the single-a or double-a start productions (S → aA or S → aaA) will miss valid strings where n = 1 or n = 2 and m is small.
Note: The solution supplied with the question was empty/absent. The grammar given above is the corrected complete solution and explains why it generates exactly the language L = { a^n b^m | n ≤ m + 3 }.
A video solution is available for this question — log in and enroll to watch it.