VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-binary-string-multiple-3-using-dfa/

⇱ Check if binary string multiple of 3 using DFA - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if binary string multiple of 3 using DFA

Last Updated : 15 Jun, 2022

Given a string of binary characters, check if it is multiple of 3 or not.
Examples : 

Input : 1 0 1 0
Output : NO
Explanation : (1 0 1 0) is 10 and hence
not a multiple of 3

Input : 1 1 0 0
Output : YES
Explanation : (1 1 0 0) is 12 and hence 
a multiple of 3

Approach 1 : One simple method is to convert the binary number into its decimal representation and then check if it is a multiple of 3 or not. Now, when it comes to DFA (Deterministic Finite Automata), there is no concept of memory i.e. you cannot store the string when it is provided, so the above method would not be applicable. In simple terms, a DFA takes a string as input and process it. If it reaches final state, it is accepted, else rejected. As you cannot store the string, so input is taken character by character.

The DFA for given problem is : 

👁 Image

As, when a number is divided by 3, there are only 3 possibilities. The remainder can be either 0, 1 or 2. Here, state 0 represents that the remainder when the number is divided by 3 is 0. State 1 represents that the remainder when the number is divided by 3 is 1 and similarly state 2 represents that the remainder when the number is divided by 3 is 2. So if a string reaches state 0 in the end, it is accepted otherwise rejected.

Below is the implementation of above approach : 


Output
YES

Time Complexity: O(n)
Auxiliary Space: O(1)

Approach 2:We will check if the difference between the number of non-zero odd bit positions and non-zero even bit positions is divisible by 3 or not.

Mathematically -> |odds-evens| divisible by 3.

Code:


Output
Yes

Time Complexity:  O(n) where n is the number of bits.

Auxiliary Space: O(1)

Comment