Count Subarrays With More Ones Than Zeros Problem
Description
LeetCode Problem 2031.
You are given a binary array nums containing only the integers 0 and 1. Return the number of subarrays in nums that have more 1's than 0's. Since the answer may be very large, return it modulo 10^9 + 7.
A subarray is a contiguous sequence of elements within an array.
Example 1:
Input: nums = [0,1,1,0,1]
Output: 9
Explanation:
The subarrays of size 1 that have more ones than zeros are: [1], [1], [1]
The subarrays of size 2 that have more ones than zeros are: [1,1]
The subarrays of size 3 that have more ones than zeros are: [0,1,1], [1,1,0], [1,0,1]
The subarrays of size 4 that have more ones than zeros are: [1,1,0,1]
The subarrays of size 5 that have more ones than zeros are: [0,1,1,0,1]
Example 2:
Input: nums = [0]
Output: 0
Explanation:
No subarrays have more ones than zeros.
Example 3:
Input: nums = [1]
Output: 1
Explanation:
The subarrays of size 1 that have more ones than zeros are: [1]
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 1
Solution
Approach: Prefix Sums + Binary Indexed Tree
Treat every 0 as -1. A subarray has more ones than zeros exactly when its sum is positive, that is, when the prefix sum at its right end is larger than the prefix sum just before its left end.
Walk through the array keeping the prefix sum s. For the current position, the number of valid subarrays ending here is the number of earlier prefix sums (including the empty prefix 0) that are smaller than s. A binary indexed tree over the possible prefix sums (shifted by n + 1 to avoid negative indexes) gives this count in O(log n): query the range below s, add it to the answer (modulo 109 + 7), then record s in the tree.
Complexity: O(n log n) time and O(n) space.
class BinaryIndexedTree:
__slots__ = ["n", "c"]
def __init__(self, n: int):
self.n = n
self.c = [0] * (n + 1)
def update(self, x: int, v: int):
while x <= self.n:
self.c[x] += v
x += x & -x
def query(self, x: int) -> int:
s = 0
while x:
s += self.c[x]
x -= x & -x
return s
class Solution:
def subarraysWithMoreOnesThanZeroes(self, nums: List[int]) -> int:
n = len(nums)
base = n + 1
tree = BinaryIndexedTree(n + base)
tree.update(base, 1)
mod = 10**9 + 7
ans = s = 0
for x in nums:
s += x or -1
ans += tree.query(s - 1 + base)
ans %= mod
tree.update(s + base, 1)
return ans