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 INPUT Binary Array nums: 1 i=0 0 i=1 1 i=2 Binary Prefixes: x0 = "1" = 1 x1 = "10" = 2 x2 = "101" = 5 nums = [1, 0, 1] ALGORITHM STEPS 1 Initialize remainder = 0 2 For each bit: rem = (rem*2 + bit) % 5 3 Check divisibility rem == 0 means div by 5 4 Store result Add true/false to answer Execution Trace: i bit rem div5? 0 1 1 false 1 0 2 false 2 1 0 true FINAL RESULT Answer Array: false 1 % 5 = 1 false 2 % 5 = 2 true 5 % 5 = 0 [0] [1] [2] Binary to Decimal: "1" = 1 (not div by 5) "10" = 2 (not div by 5) "101" = 5 (div by 5!) OK Output: [false, false, true] Only x2=5 is divisible by 5 Key Insight: Modular Arithmetic Instead of computing the full number (which can be huge), we only track the remainder mod 5. Formula: new_remainder = (old_remainder * 2 + current_bit) % 5 This works because (a*b + c) % m = ((a%m)*(b%m) + c%m) % m -- keeps numbers small! TutorialsPoint - Binary Prefix Divisible By 5 | Modular Arithmetic Approach
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