Problem 1018

Abstract / Summary

Given a binary number as a string, determine for each prefix if its decimal value is divisible by five.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1018.py

class Solution:
    def prefixesDivBy5(self, nums: List[int]) -> List[bool]:
        x = 0
        for n in nums:
            x <<= 1
            x  |= n
            x  %= 5
            yield x == 0
8 lines | 207 bytes | submitted October 21, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 54% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Bit Manipulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a method that processes a sequence of binary digits and determines, for each prefix of the sequence, whether the integer represented by that prefix is divisible by 5. The method returns a lazy iterable of Boolean values, one for each input digit, indicating the divisibility status of the corresponding prefix.

Core Logic

The algorithm maintains a running integer x that represents the value of the current prefix interpreted as a binary number. For each incoming digit n, the value is updated by left-shifting x one position (equivalent to multiplying by 2), inserting the new bit with a bitwise OR, and then reducing the result modulo 5. The Boolean result for the current prefix is produced by comparing the reduced value to zero.

x = 0
for n in nums:
    x <<= 1          # multiply current value by 2
    x |= n           # add the new binary digit
    x %= 5           # keep only the remainder modulo 5
    yield x == 0     # True if the prefix is divisible by 5

Step-by-Step Walkthrough

The method begins by initializing x to zero, establishing a clean starting point for the accumulation of bits.

x = 0

The loop iterates over each element n in the input list nums. The left-shift operation x <<= 1 moves all existing bits one position toward the most significant side, preparing the variable to receive the next digit.

x <<= 1

The bitwise OR x |= n injects the new digit into the least-significant position. Because the input is guaranteed to consist of binary digits (0 or 1), this operation correctly appends the digit to the binary representation.

x |= n

Immediately after incorporating the new digit, the algorithm applies the modulo operation x %= 5. This step is crucial: it discards any higher-order multiples of 5, ensuring that x never grows beyond the range [0, 4]. By keeping the intermediate value bounded, the method avoids integer overflow and reduces the amount of work required for subsequent iterations.

x %= 5

Finally, the method yields a Boolean value that reflects whether the current prefix is exactly divisible by 5. The expression x == 0 evaluates to True when the remainder is zero, and False otherwise.

yield x == 0

Edge-Case Handling

The implementation gracefully handles several edge conditions without additional branching logic.

When the input list nums is empty, the for loop body never executes, and the generator produces no output, which correctly represents the absence of any prefixes.

If the input contains leading zeros, the left-shift and OR operations still correctly incorporate those zeros, and the modulo reduction ensures that the intermediate value remains accurate. For example, a prefix of [0, 0, 1] yields the binary number 001, which the algorithm treats as the integer 1.

The modulo reduction after each digit guarantees that even extremely long input sequences do not cause the accumulator x to exceed the small range [0, 4]. Consequently, the method remains robust for inputs of arbitrary length, including those that would otherwise produce very large binary numbers.

Because the algorithm only uses bitwise operations and a single modulo per iteration, it naturally accommodates any combination of 0s and 1s, including alternating patterns or long runs of identical bits.

Performance Optimizations

The code exhibits several deliberate choices that enhance its runtime efficiency.

The use of a left-shift (<<=) combined with a bitwise OR (|=) provides a low-level, constant-time way to construct the next binary value from the previous one. These operations are faster than arithmetic multiplication and addition in high-level languages.

Applying the modulo operation immediately after each bit insertion prevents the accumulator from growing beyond a single digit in base 5. This boundedness eliminates the need for arbitrary-precision arithmetic, keeping each iteration’s cost low and predictable.

Returning a generator via yield enables lazy evaluation. Consumers of the method can retrieve results one at a time without materializing the entire Boolean list in memory. This approach reduces peak memory usage, especially for very large input arrays, and allows early termination if only a subset of results is needed.

Overall, the combination of bitwise manipulation, early modular reduction, and lazy result production yields a solution that scales efficiently with input size while maintaining minimal memory overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long row of building blocks, and each block has either a zero or a one written on it. The code looks at these blocks one by one to build a secret number. Every time a new block is added, the code shifts the current number to the left to make room and then places the new block at the end. After adding the block, the code checks if the big number you have built is something that can be split perfectly into five equal piles. These piles are like having five friends and making sure everyone gets exactly the same amount of cookies without any crumbs left over. If the number splits perfectly into five, the code shouts yes, and if not, it shouts no. The code keeps doing this for every single block in the row until all of them are used up.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.73 | σ = 2.14

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github aylei Rust
BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
varunu28 Java
withaarzoo C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
aylei Rust
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
varunu28 Java
withaarzoo C++
33 links | 20 authors | 9 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

2 easy
3 solutions   October 21, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality