Program to build a DFA that accepts strings starting and ending with different character
Last Updated :
14 Sep, 2022
Prerequisite: Deterministic Finite Automata
Given a string, str consists of characters 'a' & 'b'. The task is to check whether string str starts and ends with different characters or not. If it does, print 'YES' with state transitions, else print 'NO'.
Examples:
Input: ababab
Output: YES
Explanation:
The string "ababab" is starting with 'a' and ends with 'b'
Input : ababa
Output : NO
Explanation:
The string "ababab" is starting with 'a' and ends with 'a'
In DFA, there is no concept of memory, therefore we have to check the string character by character, beginning with the 0th character. The input set of characters for the problem is {a, b}. For a DFA to be valid, there must a transition rule defined for each symbol of the input set at every state to a valid state.
DFA Machine: For the above problem statement build a DFA machine. It is similar to a flowchart with various states and transitions. DFA machine corresponding to the above problem is shown below, Q2 and Q4 are the final states:

Explanation:
Suppose the first character in the input string is 'a', then on reading 'a', the control will shift to the upper branch of the machine. Now, it is defined that the string must not end with an 'a' to be accepted. At state Q1, if again 'a' comes, it keeps circling at the same state because for the machine the last read character might be the last character of the string. If it gets a 'b', then it can go to the final state, since a string ending in 'b' is acceptable in this case, so it moves to state Q2. Here, if it gets an 'a', it again enters the non-final state else for consecutive 'b's, it keeps circling in the final state.
The same is in the case when the first character is detected as 'b'.
Approach:
- Define the minimum number of states required to make the state diagram. Use functions to various states.
- List all the valid transitions. Each state must have a transition for every valid symbol.
- Define the final states by applying the base condition.
- Define all the state transitions using state function calls.
- Define a returning condition for the end of the string.
For the given DFA Machine, the specifications are as follows:
- Q0, Q1, Q2, Q3, Q4 are the defined states.
- a and b are valid symbols. Each state has a transition defined for a and b.
- Q2 and Q4 are defined as the final state. If the string input ends at any of these states, it is accepted else rejected.
- Suppose at state Q0, if 'a' comes, the function call is made to Q1. If 'b' comes, the function call is made to Q3.
- If by following the process, the program reaches the end of the string, the output is made according to the state the program is at.
Below is the implementation of the above approach:
C++
// CPP Program to DFA that accepts
// string if it starts and end with
// same character
#include <bits/stdc++.h>
using namespace std;
// various states of DFA machine
// are defined using functions.
bool q1(string, int);
bool q2(string, int);
bool q3(string, int);
bool q4(string, int);
// vector to store state transition
vector<string> state_transition;
// end position is checked using string
// length value.
// q0 is the starting state.
// q2 and q4 are intermediate states.
// q1 and q3 are final states.
bool q1(string s, int i)
{
state_transition.push_back("q1");
if (i == s.length()) {
return false;
}
// state transitions
// a takes to q1, b takes to q2
if (s[i] == 'a')
return q1(s, i + 1);
else
return q2(s, i + 1);
}
bool q2(string s, int i)
{
state_transition.push_back("q2");
if (i == s.length()) {
return true;
}
// state transitions
// a takes to q1, b takes to q2
if (s[i] == 'a')
return q1(s, i + 1);
else
return q2(s, i + 1);
}
bool q3(string s, int i)
{
state_transition.push_back("q3");
if (i == s.length()) {
return false;
}
// state transitions
// a takes to q4, 1 takes to q3
if (s[i] == 'a')
return q4(s, i + 1);
else
return q3(s, i + 1);
}
bool q4(string s, int i)
{
state_transition.push_back("q4");
if (i == s.length()) {
return true;
}
// state transitions
// a takes to q4, b takes to q3
if (s[i] == 'a')
return q4(s, i + 1);
else
return q3(s, i + 1);
}
bool q0(string s, int i)
{
state_transition.push_back("q0");
if (i == s.length()) {
return false;
}
// state transitions
// a takes to q1, b takes to q3
if (s[i] == 'a')
return q1(s, i + 1);
else
return q3(s, i + 1);
}
int main()
{
string s = "ababab";
// all state transitions are printed.
// if string is acceptable, print YES.
// else NO is printed
bool ans = q0(s, 0);
if (ans) {
cout << "YES" << endl;
// print transition state of given
// string str
for (auto& it : state_transition) {
cout << it << ' ';
}
}
else
cout << "NO" << endl;
return 0;
}
Java
// Java Program to DFA that accepts
// string if it starts and end with
// same character
import java.util.*;
class GFG
{
// vector to store state transition
static Vector state_transition = new Vector();
// end position is checked using string
// length value.
// q0 is the starting state.
// q2 and q4 are intermediate states.
// q1 and q3 are final states.
static boolean q1(String s, int i)
{
state_transition.add("q1");
if (i == s.length())
{
return false;
}
// state transitions
// a takes to q1, b takes to q2
if (s.charAt(i) == 'a')
return q1(s, i + 1);
else
return q2(s, i + 1);
}
static boolean q2(String s, int i)
{
state_transition.add("q2");
if (i == s.length())
{
return true;
}
// state transitions
// a takes to q1, b takes to q2
if (s.charAt(i) == 'a')
return q1(s, i + 1);
else
return q2(s, i + 1);
}
static boolean q3(String s, int i)
{
state_transition.add("q3");
if (i == s.length())
{
return false;
}
// state transitions
// a takes to q4, 1 takes to q3
if (s.charAt(i) == 'a')
return q4(s, i + 1);
else
return q3(s, i + 1);
}
static boolean q4(String s, int i)
{
state_transition.add("q4");
if (i == s.length())
{
return true;
}
// state transitions
// a takes to q4, b takes to q3
if (s.charAt(i) == 'a')
return q4(s, i + 1);
else
return q3(s, i + 1);
}
static boolean q0(String s, int i)
{
state_transition.add("q0");
if (i == s.length())
{
return false;
}
// state transitions
// a takes to q1, b takes to q3
if (s.charAt(i) == 'a')
return q1(s, i + 1);
else
return q3(s, i + 1);
}
// Driver code
public static void main (String[] args)
{
String s = "ababab";
// all state transitions are printed.
// if string is acceptable, print YES.
// else NO is printed
boolean ans = q0(s, 0);
if (ans == true)
{
System.out.println("YES");
// print transition state of given
// string str
for(int index = 0; index < state_transition.size(); index++)
{ //(auto& it : ) {
System.out.print((String)state_transition.get(index) + ' ');
}
}
else
System.out.println("NO");
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 Program to DFA that accepts
# if it starts and end with
# same character
# vector to store state transition
state_transition = []
# end position is checked using string
# length value.
# q0 is the starting state.
# q2 and q4 are intermediate states.
# q1 and q3 are final states.
def q1(s, i):
state_transition.append("q1")
if (i == len(s)):
return False
# state transitions
# a takes to q1, b takes to q2
if (s[i] == 'a'):
return q1(s, i + 1)
else:
return q2(s, i + 1)
def q2(s, i):
state_transition.append("q2")
if (i == len(s)):
return True
# state transitions
# a takes to q1, b takes to q2
if (s[i] == 'a'):
return q1(s, i + 1)
else:
return q2(s, i + 1)
def q3(s, i):
state_transition.append("q3")
if (i == len(s)):
return False
# state transitions
# a takes to q4, 1 takes to q3
if (s[i] == 'a'):
return q4(s, i + 1)
else:
return q3(s, i + 1)
def q4(s, i):
state_transition.append("q4")
if (i == len(s)):
return True
# state transitions
# a takes to q4, b takes to q3
if (s[i] == 'a'):
return q4(s, i + 1)
else:
return q3(s, i + 1)
def q0(s, i):
state_transition.append("q0")
if (i == len(s)):
return False
# state transitions
# a takes to q1, b takes to q3
if (s[i] == 'a'):
return q1(s, i + 1)
else:
return q3(s, i + 1)
s = "ababab"
# all state transitions are printed.
# if is acceptable, print YES.
# else NO is printed
ans = q0(s, 0)
if (ans):
print("YES")
# print transition state of given
# str
for it in state_transition:
print(it, end = " ")
else:
print("NO")
# This code is contributed by mohit kumar 29
C#
// C# Program to DFA that accepts
// string if it starts and end with
// same character
using System;
using System.Collections;
class GFG{
// vector to store state transition
static ArrayList state_transition =
new ArrayList();
// end position is checked using
// string length value.
// q0 is the starting state.
// q2 and q4 are intermediate
// states. q1 and q3 are final
// states.
static bool q1(string s, int i)
{
state_transition.Add("q1");
if (i == s.Length)
{
return false;
}
// state transitions
// a takes to q1, b
// takes to q2
if (s[i] == 'a')
return q1(s, i + 1);
else
return q2(s, i + 1);
}
static bool q2(string s, int i)
{
state_transition.Add("q2");
if (i == s.Length)
{
return true;
}
// state transitions
// a takes to q1, b takes to q2
if (s[i] == 'a')
return q1(s, i + 1);
else
return q2(s, i + 1);
}
static bool q3(string s, int i)
{
state_transition.Add("q3");
if (i == s.Length)
{
return false;
}
// state transitions
// a takes to q4, 1
// takes to q3
if (s[i] == 'a')
return q4(s, i + 1);
else
return q3(s, i + 1);
}
static bool q4(string s, int i)
{
state_transition.Add("q4");
if (i == s.Length)
{
return true;
}
// state transitions
// a takes to q4, b
// takes to q3
if (s[i] == 'a')
return q4(s, i + 1);
else
return q3(s, i + 1);
}
static bool q0(string s, int i)
{
state_transition.Add("q0");
if (i == s.Length)
{
return false;
}
// state transitions
// a takes to q1, b
// takes to q3
if (s[i] == 'a')
return q1(s, i + 1);
else
return q3(s, i + 1);
}
// Driver code
public static void Main (string[] args)
{
string s = "ababab";
// all state transitions are
// printed. If string is
// acceptable, print YES.
// else NO is printed
bool ans = q0(s, 0);
if (ans == true)
{
Console.Write("YES\n");
// print transition state
// of given string str
for(int index = 0;
index < state_transition.Count;
index++)
{
//(auto& it : ) {
Console.Write(
(string)state_transition[index] + ' ');
}
}
else
Console.Write("NO");
}
}
// This code is contributed bt rutvik_56
JavaScript
<script>
// JavaScript Program to DFA that accepts
// string if it starts and end with
// same character
// vector to store state transition
var state_transition = [];
// end position is checked using
// string length value.
// q0 is the starting state.
// q2 and q4 are intermediate
// states. q1 and q3 are final
// states.
function q1(s, i) {
state_transition.push("q1");
if (i === s.length) {
return false;
}
// state transitions
// a takes to q1, b
// takes to q2
if (s[i] === "a") return q1(s, i + 1);
else return q2(s, i + 1);
}
function q2(s, i) {
state_transition.push("q2");
if (i === s.length) {
return true;
}
// state transitions
// a takes to q1, b takes to q2
if (s[i] === "a") return q1(s, i + 1);
else return q2(s, i + 1);
}
function q3(s, i) {
state_transition.push("q3");
if (i === s.length) {
return false;
}
// state transitions
// a takes to q4, 1
// takes to q3
if (s[i] === "a") return q4(s, i + 1);
else return q3(s, i + 1);
}
function q4(s, i) {
state_transition.push("q4");
if (i === s.length) {
return true;
}
// state transitions
// a takes to q4, b
// takes to q3
if (s[i] === "a") return q4(s, i + 1);
else return q3(s, i + 1);
}
function q0(s, i) {
state_transition.push("q0");
if (i === s.length) {
return false;
}
// state transitions
// a takes to q1, b
// takes to q3
if (s[i] === "a") return q1(s, i + 1);
else return q3(s, i + 1);
}
// Driver code
var s = "ababab";
// all state transitions are
// printed. If string is
// acceptable, print YES.
// else NO is printed
var ans = q0(s, 0);
if (ans === true) {
document.write("YES <br>");
// print transition state
// of given string str
for (var index = 0; index < state_transition.length; index++) {
//(auto& it : ) {
document.write(state_transition[index] + " ");
}
} else document.write("NO");
// This code is contributed by rdtank.
</script>
Output: YES
q0 q1 q2 q1 q2 q1 q2
Time Complexity: O(n) where a string of length n requires traversal through n states.
Auxiliary Space: O(n), for storing the states in the array.
Similar Reads
Program to build a DFA to accept strings that start and end with same character Given a string consisting of characters a and b, check if the string starts and ends with the same character or not. If it does, print 'Yes' else print 'No'.Examples: Input: str = "abbaaba" Output: Yes Explanation: The given input string starts and ends with same character 'a' So the states of the b
12 min read
Program to build a DFA that accepts Strings ending with abc Given a string, str consists of characters 'a', 'b' & 'c', the task is to check whether string str ends with "abc" or not. If it does, print âAcceptedâ with state transitions, else print âNot Acceptedâ. Examples: Input: str = "cbabc"Output: AcceptedExplanation: c : q0-->q0b: q0-->q0a: q0--
11 min read
Program to build DFA that starts and end with 'a' from input (a, b) DFA (Deterministic Finite Automaton or Acceptor) is a finite state machine that accepts or rejects strings of symbols. DFA accepts the string if it reaches the final state and rejects otherwise. Now the problem is, provided a string as input character by character and we have to check whether the st
8 min read
Program to build a DFA that checks if a string ends with "01" or "10" DFA or Deterministic Finite Automata is a finite state machine which accepts a string(under some specific condition) if it reaches a final state, otherwise rejects it.Problem: Given a string of '0's and '1's character by character, check for the last two characters to be "01" or "10" else reject the
10 min read
NFA machines accepting all strings that ends or not ends with substring 'ab' Prerequisite: Basic Knowledge of NFA and state transition diagramsProblem 1:Construction of a minimal NFA accepting a set of strings over {a, b} in which each string of the language ends with 'ab'. ExplanationThe desired language will be like: L1 = {ab, abbab, abaab, ...........}Here as we can see t
2 min read