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
Count Subarrays With More Ones Than Zeros INPUT Binary Array nums: 1 i=0 0 i=1 1 i=2 1 i=3 0 i=4 Find subarrays where count(1) > count(0) Valid Subarrays: [1] at i=0 [1,0,1] at i=0-2 [1] at i=2 [1,1] at i=2-3 [1] at i=3 [1,0,1,1] at i=0-3 ... and more Transform: 0 --> -1 [1,-1,1,1,-1] ALGORITHM STEPS 1 Transform Array Convert 0 to -1 Now find sum > 0 2 Compute Prefix Sum Track running sum idx: 0 1 2 3 4 arr: 1 -1 1 1 -1 pre: 1 0 1 2 1 3 Count Smaller Prefix For each prefix[i], count prefix[j] < prefix[i] where j < i 4 Use BIT/Segment Tree Efficient counting with Binary Indexed Tree Complexity: Time: O(n log n) Space: O(n) FINAL RESULT Valid Subarrays Found: Prefix Sum Analysis: At i=0: pre=1, count=1 At i=1: pre=0, count=0 At i=2: pre=1, count=2 At i=3: pre=2, count=4 At i=4: pre=1, count=2 Total: 1+0+2+4+2 = 9 (mod 10^9 + 7) Output: 9 OK - 9 valid subarrays with more 1s than 0s Key Insight: By transforming 0s to -1s, we convert the problem to finding subarrays with positive sum. Using prefix sums, a subarray [i,j] has sum > 0 when prefix[j] > prefix[i-1]. A Binary Indexed Tree efficiently counts how many previous prefix sums are smaller than current. TutorialsPoint - Count Subarrays With More Ones Than Zeros | Prefix Sum Approach
Asked in
Google 15 Facebook 12 Amazon 8
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen