GATE / CS ARCHIVE

GATE CSE 1998 / QUESTION 3(b)

Regular expression for constrained zeros

Theory of Computation · Regular Expressions & Languages · Full GATE CSE 1998 paper

GATE 1998, Q3(b) Descriptive
Report issue

Regular Expressions & Languages

Question 3(b), GATE 1998: Give a regular expression for binary strings in which every 0 is immediately followed by exactly k consecutive 1s and preceded by at least k consecutive 1s, for fixed nonnegative integer k.
Question 3(b), GATE 1998: Give a regular expression for binary strings in which every 0 is immediately followed by exactly k consecutive 1s and preceded by at least k consecutive 1s, for fixed nonnegative integer k.
Tap to enlarge
Answer & solution

Answer: 1* ∪ 1^k 1* 0 1^k (0 1^k)*. (no official key was published)

Interpret “exactly k” as the length of the entire run of consecutive 1s immediately after a 0. Write 1k for k copies of the symbol 1, not a variable exponent inside the regex. One expression is

1* ∪ 1k 1* 0 1k (0 1k)*.

The first branch handles strings with no zeros, including ε. Their condition is vacuously true; they must not be discarded merely because they contain fewer than k ones. In the second branch, the initial run 1k1* has at least k ones, so the first zero has the required predecessor run. Every zero then contributes the block 01k. Repeating that block gives exactly k ones between consecutive zeros, simultaneously satisfying the preceding and following requirements. The last zero is also followed by exactly k ones, with no extra trailing ones.

Conversely, any valid string containing a zero has an initial run of at least k ones. After its first zero, each run of ones has length exactly k, until the string ends or the next zero begins. It therefore has the displayed form. For k=2, 11011 and 111011011 are accepted, whereas 1011 lacks enough leading ones and 110111 has too many final ones. For k=0 the formula reduces to 1*0*: no one may occur after the first zero. If “followed by k ones” meant at least k rather than exactly k, a different language would result.

Original paper, page 5