Back to posts

LeetCode Challenge Day 70 โ€” 1018. Binary Prefix Divisible By 5

Nitin Ahirwal / November 24, 2025

LeetCode ChallengeDay 70MathBit ManipulationPrefixArrayJavaScriptEasy

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:

  • true if the integer represented by nums[0..i] is divisible by 5
  • false otherwise

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

  1. Initialize:
  • prefixMod = 0
  • result = []
  1. For each bit:
prefixMod = (prefixMod * 2 + nums[i]) % 5
  1. If prefixMod === 0, push true, otherwise false

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 ๐Ÿ‘จโ€๐Ÿ’ป