A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 1018. Binary Prefix Divisible By 5, the solution in this repository is mainly a prefix sums solution.
Guide
What?
The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: prefix sums.
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are prefixesDivBy5.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 12 ms, faster than 88.68% of C++ online submissions for Binary Prefix Divisible By 5.
02//Memory Usage: 10.8 MB, less than 78.57% of C++ online submissions for Binary Prefix Divisible By 5.
03class Solution {
04public:
05 vector<bool> prefixesDivBy5(vector<int>& A) {
06 vector<bool> ans(A.size());
07 int acc = 0;
08 for(int i = 0; i < A.size(); i++){
09 //(x*2) % 5 = (x%5) * 2
10 //(x+y) % 5 = x%5 + y%5
11 acc = ((acc << 1) + A[i]) % 5;
12 if(acc == 0){
13 ans[i] = true;
14 }
15 }
16 return ans;
17 }
18};
Cost