Binary Prefix Divisible By 5 Problem
Description
LeetCode Problem 1018.
You are given a binary array nums (0-indexed).
We define x_i as the number whose binary representation is the subarray nums[0..i] (from most-significant-bit to least-significant-bit).
- For example, if
nums = [1,0,1], thenx_0 = 1,x_1 = 2, andx_2 = 5.
Return an array of booleans answer where answer[i] is true if x_i is divisible by 5.
Example 1:
Input: nums = [0,1,1]
Output: [true,false,false]
Explanation: The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.
Only the first number is divisible by 5, so answer[0] is true.
Example 2:
Input: nums = [1,1,1]
Output: [false,false,false]
Constraints:
1 <= nums.length <= 10^5nums[i]is either0or1.
Solution
Approach: Keep the Prefix Modulo 5
Each new bit turns the prefix value x into 2 * x + bit. The prefixes get as long as 105 bits, far too big for any integer type, but we only need to know whether each one is divisible by 5. Since (2 * x + bit) % 5 = (2 * (x % 5) + bit) % 5, it is enough to keep r = x % 5:
- For each bit, update
r = (2 * r + bit) % 5. - The prefix is divisible by 5 exactly when
r == 0.
Reducing at every step keeps r below 5, so nothing overflows. A common mistake is to keep the full value (or only reduce it now and then), which overflows after 32 or 64 bits.
Complexity: O(n) time, and O(1) extra space besides the answer.
class Solution:
def prefixesDivBy5(self, nums: List[int]) -> List[bool]:
answer = []
r = 0 # the current prefix's value mod 5
for bit in nums:
r = (r * 2 + bit) % 5 # appending a bit doubles the value and adds the bit
answer.append(r == 0)
return answer