#1018

Binary Prefix Divisible By 5

Easy
ArrayBit ManipulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of recalculating the decimal value for each prefix, we can build the number iteratively. We can keep a running total and use modulo 5 to check divisibility, which is more efficient.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an empty result array and a variable to hold the current number.
  2. 2Step 2: For each index i in the nums array, update the current number using the formula: current_number = (current_number * 2 + nums[i]) % 5.
  3. 3Step 3: Check if current_number is 0 (which means it's divisible by 5) and store the result in the result array.
solution.py7 lines
1# Full working Python code
2result = []
3current_number = 0
4for num in nums:
5    current_number = (current_number * 2 + num) % 5
6    result.append(current_number == 0)
7return result

Complexity note: The time complexity is O(n) because we only traverse the array once, and the space complexity is O(n) for the result array.

  • 1Divisibility by 5 can be checked using modulo operation.
  • 2Building the number iteratively avoids redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.