LeetCode Challenge Day 70 โ 1018. Binary Prefix Divisible By 5
Nitin Ahirwal / November 24, 2025
Hey folks ๐
This is Day 70 of my LeetCode streak ๐
Todayโs problem is 1018. Binary Prefix Divisible By 5 โ an easy but very elegant problem that uses modular arithmetic to avoid overflow while working with growing binary prefixes.
๐ Problem Statement
You are given a binary array nums where each element is either 0 or 1.
For each prefix nums[0..i], interpret it as a binary number, and determine whether that number is divisible by 5.
Return an array result where result[i] is:
trueif the integer represented bynums[0..i]is divisible by5falseotherwise
Example:
Input: nums = [0,1,1]
Binary prefixes:
- 0 โ 0 (divisible by 5 โ
)
- 01 โ 1 (not divisible โ)
- 011 โ 3 (not divisible โ)
Output: [true, false, false]
๐ก Intuition
Directly converting each prefix to a decimal number is tempting, but quickly becomes inefficient and can overflow for large inputs.
Instead:
- A number is divisible by 5 only if its remainder modulo 5 is 0
- When a new bit is appended, the value becomes:
newValue = oldValue * 2 + bit
- In modulo form:
(oldValue * 2 + bit) % 5 = ((oldValue % 5) * 2 + bit) % 5
So we store only the remainder mod 5, not the whole number.
๐ Approach
- Initialize:
prefixMod = 0result = []
- For each bit:
prefixMod = (prefixMod * 2 + nums[i]) % 5
- If
prefixMod === 0, pushtrue, otherwisefalse
This keeps the value small and avoids overflow.
โฑ๏ธ Complexity Analysis
| Complexity | Value | |-----------|--------| | Time | O(n) | | Space | O(n) for result, O(1) extra vars |
๐งโ๐ป Code (JavaScript)
/**
* @param {number[]} nums
* @return {boolean[]}
*/
var prefixesDivBy5 = function(nums) {
const result = [];
let prefixMod = 0; // current value modulo 5
for (let i = 0; i < nums.length; i++) {
prefixMod = (prefixMod * 2 + nums[i]) % 5;
result.push(prefixMod === 0);
}
return result;
};
๐ฏ Reflection
This problem is a great reminder that:
-
You donโt always need the exact number โ sometimes the remainder is enough
-
Modular arithmetic is a powerful tool for avoiding overflow
-
Even โeasyโ problems can teach strong math + bitwise reasoning
Thatโs it for Day 70 of my LeetCode challenge ๐ช
Keep iterating, one bit (and one day) at a time โก
Happy Coding ๐จโ๐ป