Binary Prefix Divisible By 5 - Problem

You are given a binary array nums (containing only 0s and 1s). Your task is to check each binary prefix of this array to see if it represents a number divisible by 5.

More specifically, for each index i, we define x_i as the decimal number whose binary representation is formed by the subarray nums[0..i] (from most-significant-bit to least-significant-bit).

Example: If nums = [1,0,1], then:
x_0 = 1 (binary "1")
x_1 = 2 (binary "10")
x_2 = 5 (binary "101")

Return an array of booleans answer where answer[i] is true if x_i is divisible by 5, and false otherwise.

Challenge: The binary numbers can become extremely large, so you'll need to use modular arithmetic to solve this efficiently!

Input & Output

example_1.py — Basic Case
$ Input: nums = [0,1,1]
Output: [true,false,false]
💡 Note: Binary prefixes: "0" (0), "01" (1), "011" (3). Only 0 is divisible by 5.
example_2.py — Contains Divisible by 5
$ Input: nums = [1,1,1]
Output: [false,false,false]
💡 Note: Binary prefixes: "1" (1), "11" (3), "111" (7). None are divisible by 5.
example_3.py — Multiple Matches
$ Input: nums = [0,1,1,1,1,1]
Output: [true,false,false,false,true,false]
💡 Note: Prefixes: "0"(0)✓, "01"(1), "011"(3), "0111"(7), "01111"(15)✓, "011111"(31). Values 0 and 15 are divisible by 5.

Constraints

  • 1 ≤ nums.length ≤ 105
  • nums[i] is either 0 or 1
  • The binary numbers can become extremely large (up to 105 bits)

Visualization

Tap to expand
Smart Cash Register: Modular ArithmeticDigital Displayremainder: 0ReadyMod 5 CalculatorInput Stream: [1, 0, 1, 0, 1]10101Processing...Step-by-Step Calculation:Step 1: remainder = (0 × 2 + 1) % 5 = 1 → false (1 ≠ 0)falseStep 2: remainder = (1 × 2 + 0) % 5 = 2 → false (2 ≠ 0)falseStep 3: remainder = (2 × 2 + 1) % 5 = 0 → true (0 = 0) ✓trueStep 4: remainder = (0 × 2 + 0) % 5 = 0 → true (0 = 0) ✓trueStep 5: remainder = (0 × 2 + 1) % 5 = 1 → false (1 ≠ 0)falseFinal Result: [false, false, true, true, false]🎯 Key Insight: Remainder never exceeds 4, preventing overflow!
Understanding the Visualization
1
Initialize Register
Start with remainder = 0, ready to process binary digits
2
Process Each Digit
For each new bit, update: remainder = (remainder × 2 + bit) % 5
3
Check Divisibility
If remainder = 0, the current prefix is divisible by 5!
4
Continue Processing
Remainder stays between 0-4, no overflow possible
Key Takeaway
🎯 Key Insight: By using modular arithmetic, we transform an overflow-prone problem into a simple, bounded calculation that works for any input size.
Asked in
Google 25 Amazon 18 Microsoft 12 Apple 8
28.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen