Count Subarrays With More Ones Than Zeros - Problem
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 109 + 7.
A subarray is a contiguous sequence of elements within an array.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,0,1,1,0]
›
Output:
9
💡 Note:
Subarrays with more 1s than 0s: [1] at indices (0,0), (2,2), (3,3); [1,0,1] at (0,2); [0,1] at (1,2); [1,1] at (2,3); [1,0,1,1] at (0,3); [0,1,1] at (1,3); [1,1,0] at (2,4). Total = 9 subarrays.
Example 2 — All Ones
$
Input:
nums = [1,1,1]
›
Output:
6
💡 Note:
All possible subarrays have more 1s than 0s: [1] appears 3 times, [1,1] appears 2 times, [1,1,1] appears 1 time. Total = 3+2+1 = 6 subarrays.
Example 3 — Single Element
$
Input:
nums = [0]
›
Output:
0
💡 Note:
The only subarray [0] has 0 ones and 1 zero, so 0 ≤ 1, which means it doesn't have more ones than zeros.
Constraints
- 1 ≤ nums.length ≤ 105
- nums[i] is either 0 or 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Binary array [1,0,1,1,0]
2
Process
Find all subarrays where count(1s) > count(0s)
3
Output
Total count of valid subarrays = 9
Key Takeaway
🎯 Key Insight: Transform counting problem into prefix sum problem by treating 0s as -1s
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code