↓Skip to main content
  1. LeetCode/

LeetCode 1018: Binary Prefix Divisible By 5

·1 min· ·
LeetCode Easy Array Bit-Manipulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-27

  • Submissions: Runtime Error → Time Limit Exceeded ×2 → Accepted ×4

Approach
#

Reading one more bit turns the prefix value into 2x + bit (Bit Manipulation: shift left, add the bit). Only divisibility by 5 matters, so apply % 5 each step and the number stays below 5. Rebuilding each prefix as an integer is O(n²) with numbers of thousands of bits.

My Attempts
#

Attempt 1 called join on a list of integers (TypeError); after that it rebuilt every prefix as an integer, O(n²) with ever-growing numbers, timing out twice. Keeping only the remainder passed.

Solution
#

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

Complexity
#

Time O(n), space O(1) excluding output.

Mistakes to Avoid
#

  • Reduce every step; (2x + b) mod 5 depends only on x mod 5.
  • Re-converting each prefix is O(n²) and times out.

Interview Explanation
#

Each new bit doubles the prefix and adds the bit, and only the remainder mod 5 matters, so I keep just the remainder and the number never grows. Time O(n).

Related

LeetCode 832: Flipping an Image
·2 mins
LeetCode Easy Array Two-Pointers Bit-Manipulation Matrix
LeetCode 832 note: reverse each row and invert its bits, which two pointers can do at once
LeetCode 645: Set Mismatch
·2 mins
LeetCode Easy Array Hash-Table Bit-Manipulation Sorting
LeetCode 645 note: use sums: missing = sum of 1..n - sum of the set, duplicate = array sum - sum of the set
LeetCode 136: Single Number
·1 min
LeetCode Easy Array Bit-Manipulation
LeetCode 136 note: x ^ x = 0 and x ^ 0 = x, so XOR everything; pairs cancel and the single number remains
LeetCode 1002: Find Common Characters
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 1002 note: count each word and intersect all Counters (minimum count per character), then expand
LeetCode 1005: Maximize Sum Of Array After K Negations
·1 min
LeetCode Easy Array Greedy Sorting
LeetCode 1005 note: negate the smallest value each time; once the smallest is positive, only the parity of the remaining count matters
LeetCode 1013: Partition Array Into Three Parts With Equal Sum
·2 mins
LeetCode Easy Array Greedy
LeetCode 1013 note: the total must be divisible by 3; accumulate from the left, cutting whenever the running sum hits total / 3, and succeed with at least 3 pieces