skip to content

questions

5

Under a condition grammar, one saved rule string has two parse trees — what does calling that grammar ambiguous mean?

level: middleimportance: must knowfreq 64%

answer

  1. the meaning is not pinned down
  2. same string, two shapes
  3. two distinct leftmost derivations
  4. 9 - 5 - 2 groups two ways
  5. grammar property, not language property

basics

~20 s

Ambiguity means the grammar admits two distinct parse trees for one string, so the tree — and therefore the meaning the string denotes — is not fixed by the grammar alone. Two conforming parsers may legitimately disagree.

solid answer

~50 s

A grammar is ambiguous when at least one string in its language has two distinct parse trees, equivalently two distinct leftmost derivations. The one-rule expression set `E -> E - E | number` derives `9 - 5 - 2` both as `(9 - 5) - 2` and as `9 - (5 - 2)`; the first evaluates to 2, the second to 6. Nothing in the rules chooses between them, so the meaning of a stored rule depends on which tree a given parser happened to build — which is how two evaluators written from the same grammar end up disagreeing about the same saved string. Ambiguity is a property of the grammar, not of the language: the usual repair is to rewrite the rules so only one tree is derivable, layering them by precedence and recursing on one side to pin associativity.

go deeper

for a junior

Recall the definition in one line: one string, two parse trees, under the same rules. Be able to point at a chain of minus signs as the standard example.

for a middle

Produce the witness on demand and evaluate both trees. Explain why a leftmost-versus-rightmost derivation of one tree is not evidence, and why the defect sits in the grammar rather than in a parser.

for a senior

Connect it to consequences in a running system: two services faithful to the same grammar disagreeing on stored text, a parser swap silently changing the meaning of data nobody edited.

for a principal

Treat an ambiguous grammar as an unowned specification gap. The question is not which tree is nicer but who gets to decide the meaning of already-stored text, and how that decision is pinned so a future implementation cannot re-open it.

## What ambiguity means precisely A **context-free grammar** is a set of productions that rewrite a nonterminal into a sequence of terminals and nonterminals. A **parse tree** records one way of applying those productions to produce a given string: the root is the start symbol, each internal node is a nonterminal, and each node's children are the right-hand side of the production used there. A grammar is **ambiguous** when *at least one* string in its language has **two distinct parse trees**. The quantifier matters in both directions: - It is **existential**, so a single witness string settles it. You demonstrate ambiguity by exhibiting one string and two trees, never by surveying the grammar's shape. - It says nothing about the *other* strings. Almost every string a grammar generates may have exactly one tree while a rare shape has two, and the grammar is still ambiguous. An equivalent formulation: two distinct **leftmost** derivations. That qualifier is load-bearing — see the next section. ## The witness: one rule, two trees Take the flat expression grammar `E -> E - E | number` and the string `9 - 5 - 2`. - **Left grouping.** The top `-` is the second minus; its left child derives `9 - 5`, its right child is `2`. The tree denotes `(9 - 5) - 2` = **2**. - **Right grouping.** The top `-` is the first minus; its left child is `9`, its right child derives `5 - 2`. The tree denotes `9 - (5 - 2)` = **6**. Both trees are built entirely from the two productions given, so both are legal. The grammar generates the string twice over, and it offers no rule that would prefer one shape. ## Derivations, orders and trees Candidates often reach for the wrong witness here, so keep the three notions apart: | Observation | Proves ambiguity? | Why | |---|---|---| | One tree has both a leftmost and a rightmost derivation | No | True of every grammar; it is the same tree walked in two orders | | Two derivations differ only in which nonterminal was expanded first | No | Different expansion order, same resulting tree | | Two distinct **leftmost** derivations exist for one string | **Yes** | Leftmost derivations are in one-to-one correspondence with parse trees | | Two distinct parse trees exist for one string | **Yes** | This is the definition | ## Why it bites a running system The grammar is where the meaning of stored text is specified, so an ambiguous one leaves the meaning under-specified everywhere that text is read: - Two independently written evaluators — one in a request path, one in a batch job — can each be faithful to the grammar and still compute different results for one saved rule. - Swapping the parser, or regenerating it with a different tool, can silently change what existing data means without any change to the data or to the rules as written. - The tree drives more than evaluation: error messages, highlighting, optimisation and code generation all read it, so the divergence surfaces in places nobody connected to a grammar question. - A rule that has behaved correctly for a year can flip the first time it is re-parsed, because nothing ever forced a choice. Note the honest limit: two different trees do **not** always give two different results. If the operator is associative and exact, both groupings evaluate the same and the ambiguity stays invisible until an operator that is not associative — subtraction, division, comparison chains — appears in a rule. ## A grammar property, not a language property Ambiguity is attached to the *rules*, not to the set of strings they generate. The same language usually has other grammars, and the standard repair is to write one of them: 1. **Stratify** the rules into one layer per precedence level, so a tighter operator can only be reached by descending; that removes the mixed-operator ambiguity. 2. **Recurse on one side** at each layer — left recursion forces left grouping, right recursion forces right grouping — which removes the same-operator chain ambiguity that `9 - 5 - 2` exhibits. 3. **Change the surface syntax** so grouping is explicit, for example by requiring brackets around nested operations; this changes what users may write but makes the ambiguity impossible rather than merely unreachable. The first two keep the language exactly as it was and only reduce the number of trees per string, which is what you want when rules are already stored. ## What an interviewer is listening for The definition alone is the floor. What separates answers is whether you reach for a witness immediately — one string, two trees, two values — and whether you locate the defect in the grammar rather than blaming a parser for "getting it wrong". A parser that produced either tree did nothing wrong; the grammar never told it which one to build.

  • How would you demonstrate a grammar is ambiguous in a conversation, without writing a proof?
    Exhibit one witness. Name a short string the grammar generates, draw the two parse trees, and point at the two productions that let each one exist. A single string with two trees settles it; there is no need to reason about the grammar as a whole.
  • Do the two trees for one string always produce two different results?
    No. If the operator is associative and exact, both groupings evaluate identically and the ambiguity is invisible. It shows up on operators that are not associative, on operations whose order has side effects, and anywhere else the tree itself is consumed — diagnostics, rewriting, code generation.
  • Why is "this string has a leftmost and a rightmost derivation" not evidence of ambiguity?
    Those are two orders of walking one tree, not two trees. Every grammar admits both for every string it generates. Ambiguity needs two distinct trees, or equivalently two distinct derivations that are both leftmost.

A written instruction like "cancel the order and refund the fee if the item is damaged" has two readings depending on how far the condition reaches. The words are fixed; the grouping is not, and two readers act differently on the same sentence.

saying these in an interview costs you the question

  • Says any grammar with a recursive rule is ambiguous
  • Offers a leftmost and a rightmost derivation as the two derivations
  • Claims ambiguity belongs to the language and can never be rewritten away
  • Treats the parser's habitual grouping as part of the grammar
  • Assumes the two trees must evaluate to the same value anyway
open as a page

In a rule language with optional else branches, why does "if A then if B then X else Y" parse two ways?

level: seniorimportance: must knowfreq 57%

basics

~20 s

Because the grammar lets a conditional be a statement with or without an else, the single else can attach to either if, giving two trees. Implementations settle it by convention — nearest unmatched if — and a grammar-level fix splits statements into matched and unmatched forms.

open as a page

How do you rewrite a flat expression grammar so that operator precedence and associativity follow from the rule shape?

level: middleimportance: should knowfreq 52%

basics

~20 s

Split the single expression rule into one layer per precedence level — expression, term, factor — so a tighter operator is reachable only by descending. Recurse on the left for left-associative operators and on the right for right-associative ones.

open as a page

An ambiguous condition grammar leaves two evaluators disagreeing about thousands of saved rules — how do you get to one meaning?

level: principalimportance: should knowfreq 33%

basics

~20 s

Choose the single intended reading deliberately, then make it unforgeable: pin it in the grammar, re-parse every stored rule to find the subset whose two trees differ, review that subset with its owners, and version the language rather than rewriting meanings silently.

open as a page

Why can no tool certify an arbitrary context-free grammar as unambiguous before you ship a rule language?

level: seniorimportance: nice to knowfreq 24%

basics

~20 s

Deciding whether an arbitrary context-free grammar is ambiguous is undecidable, so no checker can be both sound and complete. Tools instead search for a witness string, which can only ever find ambiguity, or restrict the grammar to a class whose successful construction proves uniqueness.

open as a page