GATE / CS ARCHIVE

SIMILAR QUESTIONS / COMPILER DESIGN

Tokenize using longest matching prefixes

2 questions solved the same way, newest first. Back to Compiler Design

How these are solved

Scan left to right, choose longest legal token at each position and exclude whitespace as specified. Token regexes, strings and requested details differ.

1 mark · NAT
Report issue

Maximal-munch lexical tokens

Lexical Analysis

Question 35, GATE 2026: Identifiers are letter(letter|digit)*; numbers are digit+; whitespace is ignored. Letters are A-Z or a-z. Tokenize x1 23mm 78 y 7z zz5 14A 8H AaYcD and count non-whitespace tokens.
Tap to enlarge
Answer & solution

Official answer: 13

Givens and goal

Identifiers are letter(letter|digit)*; numbers are digit+; whitespace is ignored. Letters are A-Z or a-z. Tokenize x1 23mm 78 y 7z zz5 14A 8H AaYcD and count non-whitespace tokens.

Approach

At each position take the longest prefix matching a token definition.

Step-by-step solution

1. A letter-starting run can include later digits, so x1, zz5, and AaYcD are each a single identifier. A digit-starting run cannot be an identifier because the initial-letter condition fails.
2. Consequently 23mm splits as number 23 then identifier mm; 7z splits as 7 and z; 14A splits as 14 and A; 8H splits as 8 and H. Whitespace is a separator but is not required at every token boundary.
3. The full sequence is x1 | 23 | mm | 78 | y | 7 | z | zz5 | 14 | A | 8 | H | AaYcD. Numbering these items gives 13 non-whitespace tokens.
4. Equivalently the nine whitespace-separated chunks contribute 1+2+1+1+2+1+2+2+1=13. The answer follows the specified lexer definitions, not any additional rules a particular programming language might impose on malformed numeric literals.

Original paper, page 23 · Answer key

2 marks · MCQ
Report issue

Longest-prefix lexical analysis

Lexical Analysis

Question 37, GATE 2018: Tokens are T1=a?(b|c)*a, T2=b?(a|c)*b, T3=c?(b|a)*c, where ? is optional. Scan bbaacabc using longest-prefix matching. Choices A T1,T2,T3; B T1,T1,T3; C T2,T1,T3; D T3,T3.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Method

At the first position T1 can consume bba: its final a ends the token before the next a. T2 can consume bb but cannot include both leading b symbols in its middle (a|c)*. T3 consumes bbaac; it cannot consume the entire input because its middle cannot contain the earlier c. Remove that five-character prefix and rescan abc, which T3 consumes completely. Longest match is decided afresh at each position, rather than choosing the earliest token pattern that can match anything.

Solution

On bbaacabc, the longest first token is bbaac, matching T3=(optional c)(a|b)*c. T1 matches only bba and T2 only bb at that position. The remaining abc also matches T3 in full, longer than the alternatives. Therefore the output is T3, T3, D.

Original paper, page 15 · Answer key