Leetcode 1018. Binary Prefix Divisible By 5
Given an array A
of binary digits (0
s and 1
s), you need to return a list of booleans answers
, where answers[i]
is true
if the binary number represented by the prefix A[0]
to A[i]
is divisible by 5.
For example:
A = [0, 1, 1]
[true, false, false]
A
?
1
to 30000
.0
or 1
) in array A
?
A
contains only 0
or 1
.true
/false
) of the same length as input array A
.num
to 0
. This variable will represent the current binary number formed by the prefix.A
, and for each digit:
num
by 1 bit and add the current digit to num
. This effectively builds the binary number.num % 5
to keep num
manageable.num
is divisible by 5, and append the result (true
or false
) to the answer list.This strategy ensures that we work with manageable numbers and avoids potential overflow issues. Modulo operation aids in keeping the number within practical bounds.
The time complexity of this approach is O(n)
, where n
is the length of the input array A
. Each element is processed exactly once.
#include <vector>
std::vector<bool> prefixesDivBy5(std::vector<int>& A) {
std::vector<bool> result;
int num = 0;
for (int digit : A) {
// Left shift num by 1 and add the current digit
num = ((num << 1) + digit) % 5;
// Check if current num is divisible by 5
result.push_back(num == 0);
}
return result;
}
Here’s the functionality breakdown:
num = ((num << 1) + digit) % 5
: This combines the current binary digit to form the number, then takes modulo 5
to keep num
in a manageable range.result.push_back(num == 0)
: Checks if the current number is divisible by 5 and stores the result.This solution is both efficient and straightforward. Each binary digit is processed in constant time, ensuring an O(n)
complexity overall.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?