Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Last active November 24, 2025 22:05
Show Gist options
  • Select an option

  • Save Ifihan/ef309fe4cdea6a3edca7e510aa221ab5 to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/ef309fe4cdea6a3edca7e510aa221ab5 to your computer and use it in GitHub Desktop.
Binary Prefix Divisible By 5

Question

Approach

To solve this, I avoid constructing the full binary number because it grows too fast, so I keep track of only its remainder mod 5. Each time I read a new bit, I update the running value using current = (current * 2 + bit) % 5, which reflects what happens when a bit is appended in binary. If the remainder becomes zero, then the entire prefix forms a number divisible by 5.

Implementation

class Solution:
    def prefixesDivBy5(self, nums: List[int]) -> List[bool]:
        result = []
        current = 0
        
        for bit in nums:
            current = (current * 2 + bit) % 5
            result.append(current == 0)
        
        return result

Complexities

  • Time: O(n)
  • Space: O(n)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment