1018. Binary Prefix Divisible By 5 LeetCode Solution

In this guide, you will get 1018. Binary Prefix Divisible By 5 LeetCode Solution with the best time and space complexity. The solution to Binary Prefix Divisible By problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Binary Prefix Divisible By solution in C++
  4. Binary Prefix Divisible By solution in Java
  5. Binary Prefix Divisible By solution in Python
  6. Additional Resources
1018. Binary Prefix Divisible By 5 LeetCode Solution image

Problem Statement of Binary Prefix Divisible By

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).

For example, if nums = [1,0,1], then x0 = 1, x1 = 2, and x2 = 5.

Return an array of booleans answer where answer[i] is true if xi is divisible by 5.

Example 1:

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.

Example 2:

Input: nums = [1,1,1]
Output: [false,false,false]

Constraints:

1 <= nums.length <= 105
nums[i] is either 0 or 1.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

1018. Binary Prefix Divisible By 5 LeetCode Solution in C++

class Solution {
 public:
  vector<bool> prefixesDivBy5(vector<int>& nums) {
    vector<bool> ans;
    int curr = 0;

    for (const int num : nums) {
      curr = (curr * 2 + num) % 5;
      ans.push_back(curr % 5 == 0);
    }

    return ans;
  }
};
/* code provided by PROGIEZ */

1018. Binary Prefix Divisible By 5 LeetCode Solution in Java

class Solution {
  public List<Boolean> prefixesDivBy5(int[] nums) {
    List<Boolean> ans = new ArrayList<>();
    int curr = 0;

    for (final int num : nums) {
      curr = (curr * 2 + num) % 5;
      ans.add(curr % 5 == 0);
    }

    return ans;
  }
}
// code provided by PROGIEZ

1018. Binary Prefix Divisible By 5 LeetCode Solution in Python

class Solution:
  def prefixesDivBy5(self, nums: list[int]) -> list[bool]:
    ans = []
    curr = 0

    for num in nums:
      curr = (curr * 2 + num) % 5
      ans.append(curr % 5 == 0)

    return ans
# code by PROGIEZ

Additional Resources

See also  1051. Height Checker LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.