Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Syntactic pattern recognition with grammars

Syntactic pattern recognition uses formal grammars (regular, context-free, etc.) and parsing algorithms (CYK, Earley, LR) to recognise structured patterns (strings, trees) and build symbolic classifiers.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Syntactic pattern recognition is used when patterns have internal structure (for example, programming languages, DNA sequences, handwriting strokes, and composed gestures). An engineer uses grammars to model valid pattern structure, and parsing algorithms to recognise or segment inputs and to build structured classifiers (often combined later with statistical or feature-based methods such as Bayesian decision theory or tree classifiers).

Key ideas

  • String: a finite sequence of symbols from an alphabet.

  • Language: a set of strings over an alphabet.

  • Grammar: a 4-tuple G = (V, Σ, R, S) where V is a finite set of nonterminal symbols, Σ is a finite set of terminal symbols (Σ ∩ V = ∅), R is a finite set of production rules of the form α → β where α ∈ (V ∪ Σ)* V (V ∪ Σ)* (i.e., α contains at least one nonterminal and α ≠ ε) and β ∈ (V ∪ Σ)*, and S ∈ V is the start symbol. State this exact definition when asked.

  • Terminal: a symbol in Σ that appears in final strings.

  • Nonterminal: a symbol in V used during derivation; it is replaced by productions.

  • Production rule: a replacement template α → β used to derive strings.

  • Derivation: starting from S, repeatedly replace a substring that matches the left side of a rule by the right side; if you get a string with only terminals, that string is in the language L(G).

  • Leftmost derivation: at each step replace the leftmost nonterminal. Rightmost derivation: replace the rightmost nonterminal.

  • Parse tree (derivation tree): a rooted ordered tree whose internal nodes are nonterminals, leaves are terminals (or ε), and children correspond to the right side of a production. When asked to draw, draw a root labelled S, expand nodes according to applied productions, label internal nodes with nonterminals and leaves with terminals; show two different trees to prove ambiguity.

  • Ambiguous grammar: a grammar G is ambiguous if there exists some string w ∈ L(G) with two different parse trees (equivalently, two distinct leftmost derivations). Emphasise: ambiguity is a property of the grammar, not of the language; however some languages are inherently ambiguous (no unambiguous grammar exists).

  • Regular grammar: a grammar whose productions are of the form A → aB, A → a or A → ε (right-linear), or A → Ba, A → a or A → ε (left-linear). Regular grammars generate regular languages (equivalent to finite automata and regular expressions).

  • Context-Free Grammar (CFG): a grammar where every production has a single nonterminal on the left: A → γ with A ∈ V and γ ∈ (V ∪ Σ)*. CFGs generate context-free languages (CFLs). Important theorem: a language is context-free iff it is accepted by some pushdown automaton (PDA) (state this exact equivalence; assumptions: standard PDAs with empty stack or final-state acceptance depending on convention).

  • Chomsky Normal Form (CNF): a CFG is in CNF if every production is of the form A → BC or A → a, with A, B, C ∈ V and a ∈ Σ; optionally S → ε allowed only if ε ∈ L(G) and S does not appear on right side. Use CNF when applying CYK.

  • Conversion to CNF: standard steps — (1) add new start symbol if S appears on right side, (2) remove ε-productions, (3) remove unit productions (A → B), (4) remove useless symbols, (5) convert long right sides by introducing new variables for terminals and factoring into binary rules. When you show this in an exam, list and apply these steps in order.

  • Parsing algorithms and complexity (assumptions stated):

    • CYK (Cocke–Younger–Kasami): works only on grammars in CNF; time complexity O(n^3 · |G|) where n = length of input string and |G| = number of productions (explain symbols).
    • Earley parser: general CFGs; worst-case O(n^3), O(n^2) for unambiguous grammars, and O(n) for almost all LR(k) grammars.
    • LR(k), SLR, LALR: deterministic bottom-up parsers for a subset of CFGs (the LR family). For LR(k) grammars parsing is O(n) time.
  • Practical use: in pattern recognition you often combine syntactic models with statistical methods — e.g., tree-structured features fed to discriminant functions or Bayesian classifiers, or use grammars to segment input before feature extraction.

Formulas

Time_CYK = O(n^3 · |G|) — n is string length (number of input symbols); |G| is number of productions. Applies to CYK on CNF.

Time_Earley = O(n^3) worst-case — n is string length; applies to general CFG parsing with Earley parser.

Time_LR = O(n) — n is string length; applies to deterministic LR grammars (no ambiguity, parser tables built beforehand).

(No SI units are applicable.)

Worked examples

Example 1 — Show ambiguity (model answer to a theory question): Question: Show that the grammar G with productions E → E + E | E * E | ( E ) | id is ambiguous by giving two different parse trees for id + id * id. Show exactly what to draw and label. Model answer (steps):

  1. State grammar and string: G as above, w = "id + id * id".
  2. First parse: assume * has higher precedence (first parse tree): draw root node labelled E. Its top production is E → E + E. The left child E maps to id (leaf id). The right child E uses E → E * E, with left child id and right child id. Draw tree with root E; its left subtree is leaf id; right subtree is internal node * with two leaf id children. Label internal nodes with applied productions.
  3. Second parse: assume + has higher precedence (second parse tree): root E → E * E. Left child E is E → E + E with two id leaves; right child E is id. Draw tree accordingly.
  4. Conclude two different parse trees exist for the same string, so grammar is ambiguous. Explain that this ambiguity arises because grammar does not encode operator precedence or associativity. (Full marks require the two trees drawn and labels of productions.)

Example 2 — Convert CFG to CNF and apply CYK (numerical-style derivation): Question: Given grammar G with start S and productions S → a S b | a b, convert to CNF and use CYK to show whether w = "aaabbb" ∈ L(G). Model answer (steps):

  1. Original grammar: S → a S b | a b. Define A → a and B → b to isolate terminals. Replace productions: S → A S B | A B A → a B → b
  2. The right-hand side of S → A S B has three symbols; convert to binary by introducing X with X → S B and replace S → A X. Final CNF productions: S → A X S → A B X → S B A → a B → b (This satisfies CNF: A → a and B → b are terminal rules; others are binary.)
  3. Apply CYK to w = a a a b b b (n = 6). Build table T[i, l] for substring starting at i of length l. Bottom row (l = 1): T[1,1] = {A}, T[2,1] = {A}, T[3,1] = {A}, T[4,1] = {B}, T[5,1] = {B}, T[6,1] = {B}.
  4. Fill l = 2 to l = 6 using rule combinations (show one representative calculation): For substring positions 3–4 ("ab") with split (3)(4): (A,B) → since S → A B, add S. So T[3,2] = {S}. For substring 3–5 ("abb"): split as (3)(4–5): (A, cell(4,2)=∅) none; split (3–4)(5): (S, B) and X → S B gives X in T[3,3]. Continue filling.
  5. After completing table we find T[1,6] contains S (show the key step: T[2,5] contained X, and T[1,1] contains A, with S → A X gives S at top). Therefore w ∈ L(G).
  6. Final answer: aaabbb is in the language. (Full marks require CNF conversion and correct CYK table or clear description of key entries leading to S at T[1,6].)

Note to reviewer: the CYK table entries are shown in text form; in an exam draw an n×n triangular table and fill cell labels.

Common mistakes

  • Confusing ambiguity of a grammar with ambiguity of a language; say "language is ambiguous" only when you can prove no unambiguous grammar exists.
  • Wrong CYK indexing: CYK uses substring length l and start index i; students swap indices or miscompute splits k.
  • Omitting the unit-production removal step when converting to CNF and then applying CYK (CYK requires exact CNF form).

For your exam

Possible question types:

  • Definitions and short notes: define grammar, CFG, CNF, parse tree, ambiguity. Full marks: precise definition, required assumptions, small example.
  • Derivations / conversions: convert given CFG into CNF (show all intermediate steps: new start, remove ε, remove unit productions, remove useless symbols, binarise rules). Full marks: all steps shown and final CNF listed.
  • Parsing algorithm application: run CYK on a given CNF grammar and string, or draw parse tree using top-down or bottom-up derivations. Full marks: correct table/trees with labels and final conclusion.
  • Construction questions: give a grammar for a specified language (regular or CFL). Full marks: grammar is correct, minimal, and justified.
  • Theoretical questions: state and explain equivalence of CFGs and PDAs or give conditions for ambiguity. Full marks: clear theorem statement and brief proof or justification.
  • Diagram questions: draw parse trees or state machines; label nodes/states and transitions. Full marks: neat drawing, labels and explanation.

Always state assumptions (e.g., whether ε allowed), name algorithms you apply (CYK needs CNF), and when you give a grammar for an exam, show how it generates strings (derive a representative string).

Quick check

  1. What is the form of productions in Chomsky Normal Form?
  2. Give one difference between a regular grammar and a context-free grammar.
  3. What is the worst-case time complexity of the CYK algorithm in terms of input length n and grammar size |G|? Answers: 1) A → BC or A → a (and optionally S → ε). 2) Regular grammar right sides have the forms A → aB or A → Ba or A → a (optionally A → ε), while CFGs allow any string of terminals and nonterminals on the right; equivalently, regular grammars generate regular languages which are a strict subset of CFLs. 3) O(n^3 · |G|).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?