Problem Description
Given a binary array, for every subarray prefix (from the beginning of the array up to the current index), determine if the number represented by that binary substring is divisible by 5. Return an array of booleans where each entry corresponds to whether the prefix number is divisible by 5.
Key Insights
- Convert the binary prefix into an integer iteratively.
- Instead of computing large numbers, maintain the remainder modulo 5.
- Use the recurrence: remainder = (remainder * 2 + current_bit) % 5.
- Check divisibility by simply testing if the remainder is 0.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the input array. Space Complexity: O(n) for the output array.
Solution
We iterate through the input binary array and update a variable that holds the current number modulo 5 using the formula: remainder = (remainder * 2 + current_bit) % 5. Since the only thing that matters for divisibility by 5 is this remainder, we avoid constructing huge numbers. For each prefix, if the remainder is 0, add true to the answer array; otherwise, add false.