Skip to content
Official PYQ · 2026

GATE CS 2026 Set 2 Q19 — Parsing (LL, LR)

Explain with AI

Which of the following grammars is/are ambiguous?

Select all correct options
View worked solution

Answer: B;C

A grammar is ambiguous if there exists at least one string in its language that has more than one leftmost derivation (or equivalently, more than one distinct parse tree).

Let's analyze each option:

  • Option A: S→aSb∣ϵS \rightarrow a S b \mid \epsilon
    This grammar generates the language L={anbn∣n≥0}L = \{a^n b^n \mid n \ge 0\}. For any string anbna^n b^n, there is exactly one unique derivation sequence (applying S→aSbS \rightarrow aSb exactly nn times followed by S→ϵS \rightarrow \epsilon). Since every string in the language has a unique parse tree, this grammar is unambiguous.
  • Option B: E→E+E∣E∗E∣idE \rightarrow E+E \mid E * E \mid id
    This is the classic expression grammar. For the string id+id∗idid + id * id, we can construct two distinct parse trees representing different operator precedences:
    • One where ++ is evaluated first: (E+E)∗E(E + E) * E
    • One where ∗* is evaluated first: E+(E∗E)E + (E * E)
    Since there is more than one parse tree for the same string, this grammar is ambiguous.
  • Option C: S→aS∣Sa∣ϵS \rightarrow a S \mid S a \mid \epsilon
    This grammar generates the language L={an∣n≥0}L = \{a^n \mid n \ge 0\}. Consider the string w=aw = a. We can derive it in two distinct ways:
    • Derivation 1: S⇒aS⇒aϵ=aS \Rightarrow aS \Rightarrow a\epsilon = a
    • Derivation 2: S⇒Sa⇒ϵa=aS \Rightarrow Sa \Rightarrow \epsilon a = a
    Since the string aa has two distinct leftmost derivations (and thus two distinct parse trees), this grammar is ambiguous.
  • Option D: S→aS∣ϵS \rightarrow a S \mid \epsilon
    This grammar generates L={an∣n≥0}L = \{a^n \mid n \ge 0\}. For any string ana^n, we must apply S→aSS \rightarrow aS exactly nn times and then terminate with S→ϵS \rightarrow \epsilon. There is no other way to derive any string, so this grammar is unambiguous.

Therefore, the ambiguous grammars are B and C.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Parsing (LL, LR) questions