Update only the prefix remainder modulo five as each bit arrives; divisibility depends on that remainder, not the full potentially large number.
Complexity
O(n) time and O(n) output space.
Report whether each binary-array prefix represents a number divisible by five.
Update only the prefix remainder modulo five as each bit arrives; divisibility depends on that remainder, not the full potentially large number.
O(n) time and O(n) output space.
package main
func prefixesDivBy5(nums []int) []bool {
result := make([]bool, len(nums))
remainder := 0
for index, bit := range nums {
remainder = (remainder*2 + bit) % 5
result[index] = remainder == 0
}
return result
}
class Solution:
def prefixesDivBy5(self, nums: list[int]) -> list[bool]:
result: list[bool] = []; remainder = 0
for bit in nums:
remainder = (remainder * 2 + bit) % 5
result.append(remainder == 0)
return result
function prefixesDivBy5(nums: number[]): boolean[] {
const result: boolean[] = []; let remainder = 0;
for (const bit of nums) { remainder = (remainder * 2 + bit) % 5; result.push(remainder === 0); }
return result;
}