Binary Prefix Divisible By 5 — LeetCode 1018 Python Solution
- Problem
- #1018
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
The 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).
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.
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), and ignoring the space consumption of the answer array, the space complexity is O(1) |
| Space | O(1) auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1018. Binary Prefix Divisible By 5 is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1018. Binary Prefix Divisible By 5?
- LeetCode 1018. Binary Prefix Divisible By 5 is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1018. Binary Prefix Divisible By 5?
- The Python solution on this page runs in O(n), and ignoring the space consumption of the answer array, the space complexity is O(1).
- What is the space complexity of LeetCode 1018. Binary Prefix Divisible By 5?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1018. Binary Prefix Divisible By 5 cover?
- LeetCode 1018. Binary Prefix Divisible By 5 is tagged Bit Manipulation and Array on LeetCode.