VOOZH about

URL: https://www.geeksforgeeks.org/theory-of-computation/program-to-construct-a-dfa-which-accepts-the-language-having-all-a-before-all-b/

⇱ Program to construct a DFA which accepts the language having all 'a' before all 'b' - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to construct a DFA which accepts the language having all 'a' before all 'b'

Last Updated : 23 Jul, 2025

Given a string S, the task is to design a for accepting the language L = {aNbM | N ≥ 0, M ≥ 0, N+M ≥ 1}. , i.e., a regular language L such that all 'a' occur before the first occurrence of 'b' {a, ab, aab, bb..., }. If the given string follows the given language L, then print “Accepted”. Otherwise, print “Not Accepted”.

Examples

Input: S = "aabbb"
Output: Accepted
Explanation: All the 'a' come before 'b' s.

Input: S = "ba"
Output: Not Accepted
Explanation: 'b' comes before 'a'.

Input: S = "aaa"
Output: Accepted
Explanation: Note that 'b' does not need to occur in S

Input: S = "b"
Output: Accepted
Explanation: Note that 'a' does not need to occur in S

Approach: The problem can be accepted only when the following cases are met:

  • All the characters can be 'a'.
  • All the characters can be 'b'.
  • All the 'b' come occur after all the 'a'.
  • There is at least one character in the string.

This can be better visualized with the help of the state transition diagram of the DFA

State Transition Diagram:

👁 Image
State Transition Diagram of the above DFA

Below is the implementation of the above approach:


Output
NOT ACCEPTED

Time Complexity: O(N) where N is the length of the string
Auxiliary Space: O(1)

Comment
Article Tags:

Explore