Problem Description
Given a binary array nums (containing only 0’s and 1’s), count how many subarrays have more 1’s than 0’s. Since the answer can be very large, return it modulo 10^9 + 7.
Key Insights
- Transform the array by converting 0’s to -1 and keeping 1’s as 1.
- Use prefix sums so that the condition “more 1’s than 0’s” becomes “subarray sum > 0.”
- The problem reduces to counting the number of pairs (i, j) with i < j such that prefix[j] > prefix[i].
- This can be efficiently solved using a Binary Indexed Tree (Fenwick Tree) or merge sort based inversion counting, with coordinate compression to handle negative prefix sums.
Space and Time Complexity
Time Complexity: O(n log n) due to BIT queries/updates or merge sort based counting.
Space Complexity: O(n) for storing prefix sums and BIT data structure.
Solution
We start by transforming the binary array: convert each 0 to -1 and each 1 remains as 1. Create a prefix sum array P where P[0] = 0 and for 1 ≤ i ≤ n, P[i] = P[i-1] + (transformed value at i-1).
The requirement “more 1’s than 0’s” for a subarray from i to j translates to P[j+1] - P[i] > 0, or equivalently P[i] < P[j+1].
Thus, the goal is to count how many pairs of indices (i, j+1) satisfy i < j+1 and P[i] < P[j+1].
To count such pairs efficiently:
- Use coordinate compression on the prefix sums to map them to a continuous range.
- Use a BIT to keep a frequency count of prefix sums encountered.
- As you iterate through the prefix sum array, for each prefix P[j], query the BIT for the count of earlier prefix sums that are smaller than P[j]. Add this count to the result, then update the BIT with P[j].
- Finally, return the computed result modulo 10^9+7.