Check whether a huge binary string is divisible by 3
Company: Adobe
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Other
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.
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: ('0',)
Expected Output: True
Explanation: Zero is divisible by 3; this is the smallest valid input.
Input: ('1',)
Expected Output: False
Explanation: The value 1 leaves remainder 1; a solution that skips the first bit would wrongly return True.
Hints
- The number can have up to 10^9 bits, far beyond any built-in integer type, so look for a small amount of information about each prefix of s that is enough to answer the question.
- Work through the examples by hand, reading "110" and "1001" one bit at a time from the left, and watch how the value of the prefix changes with each new bit.
- Remember that "0" is a valid input and represents zero, which is divisible by 3.