Magicsheet logo

Count Subarrays With More Ones Than Zeros

Medium
25%
Updated 8/1/2025

Count Subarrays With More Ones Than Zeros

What is this problem about?

The "Count Subarrays With More Ones Than Zeros interview question" asks you to find the number of subarrays where the count of '1's is strictly greater than the count of '0's. You are given a binary array. This problem is an extension of finding subarrays with an equal number of zeros and ones, but it introduces an inequality constraint.

Why is this asked in interviews?

Google uses the "Count Subarrays With More Ones Than Zeros coding problem" to test a candidate's ability to optimize beyond a simple hash map. While equal counts can be solved in O(N)O(N) with a map, the "more than" condition requires an O(NlogN)O(N \log N) or O(N)O(N) approach using a Binary Indexed Tree (BIT) or Segment Tree. It evaluations your mastery of range-based frequency queries.

Algorithmic pattern used

This problem follows the Prefix Sum and Range Counting pattern.

  1. Transformation: Treat '0' as -1 and '1' as +1.
  2. The Condition: We need to find the number of pairs (i,j)(i, j) with i<ji < j such that prefixSum[j] - prefixSum[i] > 0, which means prefixSum[j] > prefixSum[i].
  3. Range Query:
    • Iterate through the prefix sums.
    • For the current sum SS, we need to count how many previous prefix sums were strictly less than SS.
    • Use a Binary Indexed Tree or Segment Tree to store the counts of seen prefix sums.
    • Perform a query(S-1) to get the count of values smaller than the current one.
    • Update the BIT with the current sum SS.

Example explanation

Array: [1, 0, 1]

  • Transformed: [1, -1, 1]
  • Prefix Sums: [0, 1, 0, 1]
  • Scan prefix sums:
    • 0: BIT has nothing. Update BIT with index 0.
    • 1: Query BIT for values < 1. Found 0 (count 1). Total = 1. Update BIT with 1.
    • 0: Query BIT for values < 0. Found nothing. Update BIT with 0.
    • 1: Query BIT for values < 1. Found 0 (count 2). Total = 1 + 2 = 3. Result: 3. (Subarrays: [1], [1], [1, 0, 1]).

Common mistakes candidates make

  • O(N2)O(N^2) Brute Force: Checking every subarray sum.
  • Coordinate Compression: Failing to handle negative prefix sums when using a BIT (requires adding an offset or using a dynamic BIT/Segment Tree).
  • Equality Confusion: Including cases where zeros == ones when the requirement is strictly "more ones."

Interview preparation tip

Master the "Binary Indexed Tree interview pattern." It is the most efficient way to handle "count elements smaller than current" problems. If you can explain how a BIT handles range updates and queries in O(logN)O(\log N), you will stand out in technical rounds.

Similar Questions