Imagine you're analyzing a series of binary signals where 1 represents success and 0 represents failure. Your task is to find all possible contiguous segments where successes outnumber failures.

Given a binary array nums containing only 0s and 1s, return the number of subarrays that have more 1's than 0's. Since the answer could be astronomically large, return it modulo 109 + 7.

What's a subarray? A subarray is any contiguous sequence of elements within the array. For example, in [1,0,1], the subarrays are: [1], [0], [1], [1,0], [0,1], and [1,0,1].

Input & Output

example_1.py โ€” Basic Case
$ Input: [1, 0, 1]
โ€บ Output: 2
๐Ÿ’ก Note: Valid subarrays are [1] and [1, 0, 1]. The subarray [1] has 1 one and 0 zeros. The subarray [1, 0, 1] has 2 ones and 1 zero.
example_2.py โ€” All Ones
$ Input: [1, 1, 1]
โ€บ Output: 6
๐Ÿ’ก Note: All possible subarrays have more ones than zeros: [1], [1], [1], [1,1], [1,1], [1,1,1]. That's 6 total subarrays.
example_3.py โ€” Mixed Array
$ Input: [1, 0, 1, 1, 0]
โ€บ Output: 9
๐Ÿ’ก Note: Valid subarrays: [1], [1,0,1], [1,0,1,1], [1], [1,1], [1,1,0], [1], [1,0], [1,0,1,1,0]. Total count is 9.

Visualization

Tap to expand
๐Ÿ€ Basketball Season AnalysisGame Results: W L W W LWLWWLPoints: +1 -1 +1 +1 -1+1-1+1+1-1Running Score: 0 โ†’ 1 โ†’ 0 โ†’ 1 โ†’ 2 โ†’ 1012+10+1+2+1Counting Winning Sequences:โ€ข Score 1: count previous scores < 1 โ†’ [0] โ†’ 1 sequenceโ€ข Score 0: count previous scores < 0 โ†’ [] โ†’ 0 sequencesโ€ข Score 1: count previous scores < 1 โ†’ [0,0] โ†’ 2 sequencesโ€ข Score 2: count previous scores < 2 โ†’ [0,1,0,1] โ†’ 4 sequencesโ€ข Score 1: count previous scores < 1 โ†’ [0,0] โ†’ 2 sequences๐ŸŽฏ Total: 1 + 0 + 2 + 4 + 2 = 9 winning sequences!
Understanding the Visualization
1
Transform the Problem
Convert losses to -1 points, wins stay +1. Now we need sequences with positive total points.
2
Track Running Score
Calculate cumulative score after each game. This gives us prefix sums.
3
Count Winning Streaks
For each game, count how many previous scores were lower than current score.
Key Takeaway
๐ŸŽฏ Key Insight: Transform the problem mathematically - convert 0s to -1s and use prefix sums to efficiently count subarrays with positive sums, which correspond to sequences where wins outnumber losses.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n log n)

O(n) for traversal, but we need O(log n) for each lookup to count smaller elements, achieved using ordered data structures

n
2n
โšก Linearithmic
Space Complexity
O(n)

Hash map to store all prefix sum frequencies

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • nums[i] is either 0 or 1
  • Return answer modulo 109 + 7
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
21.8K Views
Medium Frequency
~25 min Avg. Time
842 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