Check if binary string multiple of 3 using DFA in Python

A Deterministic Finite Automaton (DFA) can efficiently check if a binary string represents a number divisible by 3. The DFA uses three states representing remainders 0, 1, and 2 when dividing by 3.

So, if the input is like n = [1, 1, 0, 0] (binary of 12), then the output will be True.

DFA Structure

The DFA has three states corresponding to remainders when dividing by 3 ?

0 1 2 0 1 0 1 0 1 Start

State 0 is both the initial and accepting state. When we end in state 0, the number is divisible by 3.

Algorithm

The algorithm processes each binary digit and transitions between DFA states ?

  • Start in state 0 (remainder 0)
  • For each binary digit, transition according to the DFA
  • If final state is 0, the number is divisible by 3

Implementation

def solve(nums):
    dfa_state = 0
    
    for digit in nums:
        if dfa_state == 0:
            if digit == 1:
                dfa_state = 1
        elif dfa_state == 1:
            if digit == 0:
                dfa_state = 2
            else:
                dfa_state = 0
        elif dfa_state == 2:
            if digit == 0:
                dfa_state = 1
            else:
                dfa_state = 0
    
    return dfa_state == 0

# Test with binary representation of 12
n = [1, 1, 0, 0]
print(f"Binary {n} divisible by 3: {solve(n)}")

# Test with binary representation of 9 
n2 = [1, 0, 0, 1] 
print(f"Binary {n2} divisible by 3: {solve(n2)}")

# Test with binary representation of 7
n3 = [1, 1, 1]
print(f"Binary {n3} divisible by 3: {solve(n3)}")
Binary [1, 1, 0, 0] divisible by 3: True
Binary [1, 0, 0, 1] divisible by 3: True
Binary [1, 1, 1] divisible by 3: False

How It Works

The DFA leverages the mathematical property that when reading a binary number left-to-right, each new bit effectively doubles the current value and adds the bit value. The states track the remainder modulo 3 ?

  • State 0: Current remainder is 0 (divisible by 3)
  • State 1: Current remainder is 1
  • State 2: Current remainder is 2

State Transition Logic

Current State Input 0 Input 1
0 0 1
1 2 0
2 1 0

Conclusion

The DFA approach provides an elegant O(n) solution to check divisibility by 3 for binary strings. The algorithm uses constant space and processes each bit once, making it efficient for large binary numbers.

Updated on: 2026-03-25T14:23:33+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements