Leetcode #1018: Binary Prefix Divisible By 5
In this guide, we solve Leetcode #1018 Binary Prefix Divisible By 5 in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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).
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Bit Manipulation, Array
Intuition
The problem structure lets us track state with bitwise operations.
Bit operations are constant time and avoid extra memory.
Approach
Apply XOR/AND/OR and shifts to maintain the required invariant.
Aggregate the result in a single pass.
Steps:
- Identify a bitwise invariant.
- Combine values with bit operations.
- Return the aggregated result.
Example
Input: nums = [0,1,1]
Output: [true,false,false]
Explanation: The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.
Only the first number is divisible by 5, so answer[0] is true.
Python Solution
class Solution:
def prefixesDivBy5(self, nums: List[int]) -> List[bool]:
ans = []
x = 0
for v in nums:
x = (x << 1 | v) % 5
ans.append(x == 0)
return ans
Complexity
The time complexity is , and ignoring the space consumption of the answer array, the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.