Quiz 2
Registry Synced

CFG to PDA Conversion and PDA to CFG

487 words
2 min read

Reading compass

Now · 🎯 Learning Objectives

CFG to PDA Conversion and PDA to CFG

🎯 Learning Objectives

  • Convert any CFG to an equivalent PDA
  • Convert any PDA to an equivalent CFG
  • Trace the conversion step by step
  • Understand the equivalence proof

1. CFG → PDA Conversion

1.1 Construction

Given CFG G = (V, Σ, R, S), construct PDA P:
  1. Push $ (bottom) then push S (start symbol)
  2. Repeat:
    • If top of stack is variable A: pop A, push RHS of some A → α (nondeterministically)
    • If top of stack is terminal a: read input a, pop a (they must match)
    • If $ on top and input empty: accept

1.2 Worked Example: S → 0S1 | ε

Transitions:
  1. (q0, ε, ε) → (q1, $) — init bottom marker
  2. (q1, ε, S) → (q1, 1S0) — S → 0S1 (push RHS reversed: 1S0)
  3. (q1, ε, S) → (q1, ε) — S → ε
  4. (q1, 0, 0) → (q1, ε) — match terminal 0
  5. (q1, 1, 1) → (q1, ε) — match terminal 1
  6. (q1, ε, $) → (q2, ε) — accept

1.3 Tracing: Input "0011"

StepStateInputStackAction
0q00011εStart
1q10011$SPush $, S
2q10011$1S0Replace S→0S1
3q1011$1SMatch 0
4q1011$1 1S0Replace S→0S1
5q111$1 1SMatch 0
6q111$1 1Replace S→ε
7q11$1Match 1
8q1ε$Match 1
9q2εεAccept (pop $)

2. PDA → CFG Conversion

2.1 Construction

Given PDA P, construct CFG G with:
  • Variables: [pXq] (state p, pop X, go to state q)
  • Start: [q0$qaccept]
  • Rules encode transitions For transition δ(p, a, X) = (q, Y1Y2...Yk):
  • Add rule: [pXr] → a[qY1r1][r1Y2r2]...[r_{k-1}Yk r]
  • For all intermediate states r1, r2, ..., rk

3. Key Concepts Reference

DirectionMethodComplexity
CFG → PDAPush start, simulate leftmost derivationO(1) per rule
PDA → CFGThree-indices variablesO(n³) states
EquivalenceBoth directions provenSame language class

4. 📝 Practice Questions

Q1: Convert S → aSb | ε to a PDA and trace for "ab".
Answer:
Transitions: (q0,ε,ε)→(q1,),(q1,ε,S)(q1,bSa),(q1,ε,S)(q1,ε),(q1,a,a)(q1,ε),(q1,b,b)(q1,ε),(q1,ε,), (q1,ε,S)→(q1,bSa), (q1,ε,S)→(q1,ε), (q1,a,a)→(q1,ε), (q1,b,b)→(q1,ε), (q1,ε,)→(q2,ε)
Trace "ab": Step 0: q0, ab, ε Step 1: q1, ab, SStep2:q1,ab,S Step 2: q1, ab,bSa (S→aSb) Step 3: q1, b, bS(matcha)Step4:q1,b,bS (match a) Step 4: q1, b,b (S→ε) Step 5: q1, ε, $ (match b) Step 6: q2, ε, ε (accept) Q2: Why must the RHS be pushed in reverse order?
Answer: The stack is LIFO (Last In, First Out). If we have a production A → αβ (where α and β are terminals/variables), we want α to be popped and matched next. Since stack pops from the top, we push β first (deeper in stack), then α (on top). This way α gets processed before β, maintaining derivation order.

5. 🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.