CS Atlas GATE 2027
TOC course
0 / 91 complete

TOC/Phase 3 · CFG, PDA & Context-Free Languages

Lesson 3.1.2 · Item 48 of 91

Writing CFGs for standard languages

Read at your own pace. Try the questions before opening the answers.

On this page

Recall warm-up

  1. How many parse trees correspond to one leftmost derivation?
    Stuck? Peek at 3.1.1 Context-free grammars, derivations and parse trees
    • CFG: A → α, single variable on the left. CFL = L(G) for some CFG. Regular ⊂ CFL.
    • Leftmost / rightmost derivations; parse tree with yield = leaves left to right.
    • Trees ↔ leftmost derivations ↔ rightmost derivations (one-to-one per string).

    Read lesson 3.1.1

  2. Grammar for palindromes over {a,b}?
    Stuck? Peek at 2.3.1 What a grammar is
    • G = (V, T, P, S); A → x | y; sentential form; ⇒, ⇒*; L(G) = {w ∈ T* : S ⇒* w}.
    • S → aSb | ε gives aⁿbⁿ (not regular) — general grammars exceed DFAs.
    • Palindromes: S → aSa | bSb | a | b | ε.

    Read lesson 2.3.1

  3. Why is aⁿbⁿ not regular (pumping view)?
    Stuck? Peek at 2.4.3 Pumping lemma for regular languages
    • L regular ⇒ ∃p ∀w ∈ L, |w| ≥ p, ∃ xyz: |xy| ≤ p, |y| ≥ 1, ∀i ≥ 0: xyⁱz ∈ L. p = #states.
    • Game: they pick p and split; you pick w and i. Beat every split.
    • Standard picks: aᵖbᵖ; a^{p²}; aᵖbaᵖb (ww); prime q ≥ p+2 with i = q+1.
    • Necessary, not sufficient. Finite languages pass vacuously.

    Read lesson 2.4.3

The Hook

GATE regularly shows a grammar and asks “which language does it generate?”, or gives a language and four grammars. The trick is that CFGs build strings with a few patterns: wrap (grow both ends together), concatenate (glue independent parts), choose (union), and repeat. Recognize the pattern and both directions become fast.

Predict First

How would you generate { aⁿb²ⁿ : n ≥ 0 } with one variable?

Core Concept

Prediction check

S → aSbb | ε. Every a placed on the left is paired with two b’s on the right, wrapping from the outside in.

SaSaSεbbbb
a²b⁴: each wrap adds one a and two b’s.

Pattern 1 — wrap (matched counts)

{aⁿbⁿ}: S → aSb | ε. {aⁿbᵐcᵐdⁿ}: S → aSd | T, T → bTc | ε (outer wrap, then inner wrap). Wrapping always matches a block on the left with a block on the right, nested.

SaSTbTεcd
abcd from S → aSd | T, T → bTc | ε: the outer pair a…d, then the inner pair b…c.

Pattern 2 — palindromes

Even: S → aSa | bSb | ε. All: add | a | b for the middle symbol. Palindromes are a wrap where both ends must be the same symbol.

SaSbSaba
ababa: wrap a…a, then b…b, then the middle symbol a — an odd-length palindrome.

Pattern 3 — balanced parentheses

S → SS | (S) | ε (concatenate balanced pieces, or wrap one). An unambiguous alternative: S → (S)S | ε.

SS(S(Sε))S(Sε)
(())() = two balanced pieces side by side, the first one wrapped twice.

Pattern 4 — equal numbers of a’s and b’s

S → aSbS | bSaS | ε. Idea: look at the first symbol; if it is a, find the b that “balances” it; between them and after them are again balanced strings. Also correct: S → SS | aSb | bSa | ε.

abbaabab — matches the first aS: balanced rest (baab)
abbaab = a · S(=ε) · b · S(=baab). The first symbol and its balancing partner split the string.

Pattern 5 — unequal counts

{aⁱbʲ : i ≠ j} = {more a’s} ∪ {more b’s}. S → AC | CB, C → aCb | ε (equal core), A → aA | a (extra a’s, at least one), B → bB | b (extra b’s).

Union of grammars: new start S → S₁ | S₂. Concatenation: S → S₁S₂. Star: S → S₁S | ε.

A
a⁺ extra a’s
followed by
C
aᵏbᵏ equal core
=
AC
aⁱbʲ with i > j
C
equal core
followed by
B
b⁺ extra b’s
=
CB
aⁱbʲ with i < j
Unequal = more a’s OR more b’s; each side is “equal core” plus extras.

Putting it together

  • Four building moves: wrap, glue, choose, repeat.
  • Wraps give nested matching; two counts that cross (aⁿbᵐcⁿdᵐ) cannot be wrapped.
  • Always test ε and the shortest strings against a grammar.

Visual

language                      grammar                                 pattern
aⁿbⁿ                          S → aSb | ε                              wrap
aⁿb²ⁿ                         S → aSbb | ε                             wrap 1:2
aⁿbᵐcᵐdⁿ                      S → aSd | T,  T → bTc | ε               nested wraps
aⁿbⁿcᵐdᵐ                      S → XY, X → aXb | ε, Y → cYd | ε         concatenation
palindromes                   S → aSa | bSb | a | b | ε                symmetric wrap
balanced ( )                  S → SS | (S) | ε                         concat + wrap
#a = #b                       S → aSbS | bSaS | ε                      split at partner
aⁱbʲ, i ≠ j                   S → AC | CB, C → aCb | ε, A → aA|a, B → bB|b   union
aⁱbʲcᵏ, i = j or j = k        S → XC | AY, X → aXb | ε, Y → bYc | ε, A → aA | ε, C → cC | ε

Worked Examples

Easy

CFG for { aⁿ c bⁿ : n ≥ 0 }.

Show the full solution

S → aSb | c. Derive aacbb: S ⇒ aSb ⇒ aaSbb ⇒ aacbb.

Medium

CFG for { aⁱbʲcᵏ : i + k = j }.

Show the full solution

Split j into the part matched with a’s and the part matched with c’s: aⁱbⁱ bᵏcᵏ. S → XY, X → aXb | ε, Y → bYc | ε. Check abbc: X ⇒ ab, Y ⇒ bc ✓. Check aab b? a²b²c⁰ ✓; abc: i + k = 2 ≠ 1 ✗ (not derivable since X, Y each give equal counts).

GATE-level

Which language does G generate? S → aSa | aSb | bSa | bSb | c.

Show the full solution

Every step adds one symbol on each side, any symbols, and the middle is c. So L = { x c y : x, y ∈ {a,b}*, |x| = |y| } — strings with c exactly in the middle position (and no other c). Not a palindrome condition: the symbols are independent.

GATE Traps

  • “Wrap” matches nested pairs: S → aSb generates aⁿbⁿ, never (ab)ⁿ-style interleavings.
  • aSa | aSb | bSa | bSb only matches lengths, not symbols.
  • For i ≠ j, don’t forget both sides of the union; each side needs at least one extra symbol.
  • Test ε against every grammar: does S → … | ε let it in?

Memory Hook

Grammar patterns are moves in a game of building: wrap (both ends), glue (side by side), choose (union), repeat (star).

Connect the Dots

Some of these grammars give two different trees for the same string (S → SS | (S) | ε does, for ()()()). When a grammar does that, it is ambiguous — the topic of the next lesson, and a real problem for compilers.

Self-Test

  1. MCQ

    Which grammar generates { aⁿbⁿ⁺¹ : n ≥ 0 }?

    1. S → aSb | b
    2. S → aSb | ε
    3. S → aSbb | b
    4. S → aS | b
  2. MSQ

    S → aSbS | bSaS | ε generates which strings?

    1. abab
    2. aabb
    3. abba
    4. aab
  3. MCQ

    S → XY, X → aXb | ε, Y → cYd | ε generates:

    1. aⁿbⁿcⁿdⁿ
    2. aⁿbⁿcᵐdᵐ
    3. aⁿbᵐcᵐdⁿ
    4. aⁿbᵐcⁿdᵐ
  4. NAT

    Number of strings of length 4 generated by S → aSa | bSb | ε?

    Write your answer before opening the key.

Rule Card

  • Wrap: S → aSb | ε (aⁿbⁿ); ratios S → aSbb.
  • Nested: outer wrap → inner wrap. Concatenation: S → XY. Union: S → S₁ | S₂. Star: S → S₁S | ε.
  • Palindromes S → aSa | bSb | a | b | ε. Balanced S → SS | (S) | ε. #a = #b: S → aSbS | bSaS | ε.
  • i ≠ j: S → AC | CB, C → aCb | ε, A → aA | a, B → bB | b.

Concept Ledger

  • wrap pattern
  • nested and concatenated grammars
  • union / concatenation / star of CFGs
  • balanced-parentheses grammar
  • equal-count grammar

Answer Vault

Reveal answers when you’re ready

Warm-up answers

  1. Exactly one.
  2. S → aSa | bSb | a | b | ε.
  3. y lies in the a’s, pumping changes only the a-count.

Self-test answers

  1. A — The final b is the extra one.
    • B: Equal counts.
    • C: Two b’s per a.
    • D: a*b.
  2. ABC — Exactly the strings with #a = #b.
    • D: 2 a’s, 1 b.
  3. B — Two independent wraps, concatenated.
    • A: n and m are independent.
    • C: That needs nesting.
    • D: Crossing pairs — not even context-free.
  4. 4 — Even palindromes of length 4: aaaa, abba, baab, bbbb.

Flashcards

  1. CFG for aⁿbⁿcᵐdᵐ?
    Reveal answerS → XY, X → aXb | ε, Y → cYd | ε
  2. CFG for aⁱbʲ with i ≠ j?
    Reveal answerS → AC | CB, C → aCb | ε, A → aA | a, B → bB | b
  3. CFG for strings with #a = #b?
    Reveal answerS → aSbS | bSaS | ε
  4. CFG for balanced parentheses?
    Reveal answerS → SS | (S) | ε (unambiguous: S → (S)S | ε)

Ready for the next idea?

Mark this item complete when you’ve finished reading and working through it.