Binary Prefix Divisible By 5 - Problem

You are given a binary array nums (0-indexed). We define xi as the number whose binary representation is the subarray nums[0..i] (from most-significant-bit to least-significant-bit).

For example, if nums = [1,0,1], then x0 = 1, x1 = 2, and x2 = 5.

Return an array of booleans answer where answer[i] is true if xi is divisible by 5.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,0,1]
Output: [false,false,true]
💡 Note: Binary prefixes: [1]→1 (not divisible by 5), [1,0]→2 (not divisible by 5), [1,0,1]→5 (divisible by 5)
Example 2 — All Zeros
$ Input: nums = [0,1,1]
Output: [true,false,false]
💡 Note: Binary prefixes: [0]→0 (divisible by 5), [0,1]→1 (not divisible by 5), [0,1,1]→3 (not divisible by 5)
Example 3 — Longer Sequence
$ Input: nums = [1,1,1,0,1]
Output: [false,false,false,false,false]
💡 Note: Binary prefixes: [1]→1, [1,1]→3, [1,1,1]→7, [1,1,1,0]→14, [1,1,1,0,1]→29. None are divisible by 5

Constraints

  • 1 ≤ nums.length ≤ 3 × 104
  • nums[i] is either 0 or 1

Visualization

Tap to expand
Binary Prefix Divisible By 5: Process OverviewInput: [1, 0, 1] → Check each prefix for divisibility by 5101Prefix: [1]Decimal: 11 % 5 ≠ 0Prefix: [1,0]Decimal: 22 % 5 ≠ 0Prefix: [1,0,1]Decimal: 55 % 5 = 0 ✓falsefalsetrueOutput: [false, false, true]
Understanding the Visualization
1
Input
Binary array [1,0,1]
2
Process
Check each prefix: [1]→1, [1,0]→2, [1,0,1]→5
3
Output
Boolean array showing divisibility by 5
Key Takeaway
🎯 Key Insight: Use modular arithmetic to track remainder % 5 instead of full decimal values
Asked in
Google 15 Amazon 12 Facebook 8
28.5K Views
Medium Frequency
~15 min Avg. Time
845 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