Check whether a huge binary string is divisible by 3

Quick Overview

Decide whether a binary string of up to a billion bits represents a number divisible by 3, without converting it to an integer. It tests modular arithmetic, keeping a running value over a stream of bits, and scanning in constant space.

Check whether a huge binary string is divisible by 3

Company: Adobe

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Given a binary string `s`, decide whether the number it represents is divisible by 3. Return `True` if it is and `False` otherwise. The string can be very long (up to ${10^9}$ characters), so converting it to an integer first may not be feasible. ### Function Signature ```python def is_divisible_by_3(s: str) -> bool: ``` ### Rules - `s` is an unsigned binary number written with the most significant bit first. - `"0"` represents zero, which is divisible by 3. ### Constraints - `1 <= len(s) <= 10^9` - `s` consists only of `'0'` and `'1'`. - `s` has no leading zeros, except when `s` is `"0"` itself. ### Examples ```text Input: s = "110" Output: True ``` `"110"` is 6 in decimal. 6 divided by 3 is 2 with no remainder. ```text Input: s = "101" Output: False ``` `"101"` is 5 in decimal. 5 divided by 3 is 1 with remainder 2. ```text Input: s = "1001" Output: True ``` `"1001"` is 8 + 1 = 9, which is 3 times 3.

Overview: Decide whether a binary string of up to a billion bits represents a number divisible by 3, without converting it to an integer. It tests modular arithmetic, keeping a running value over a stream of bits, and scanning in constant space.

Adobe logo
Adobe
Nov 24, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Given a binary string s, decide whether the number it represents is divisible by 3. Return True if it is and False otherwise.

The string can be very long (up to 109{10^9} characters), so converting it to an integer first may not be feasible.

Function Signature

def is_divisible_by_3(s: str) -> bool:

Rules

  • s is an unsigned binary number written with the most significant bit first.
  • "0" represents zero, which is divisible by 3.

Constraints

  • 1 <= len(s) <= 10^9
  • s consists only of '0' and '1' .
  • s has no leading zeros, except when s is "0" itself.

Examples

Input: s = "110"
Output: True

"110" is 6 in decimal. 6 divided by 3 is 2 with no remainder.

Input: s = "101"
Output: False

"101" is 5 in decimal. 5 divided by 3 is 1 with remainder 2.

Input: s = "1001"
Output: True

"1001" is 8 + 1 = 9, which is 3 times 3.