KatInterview

510. Count Subarrays With More Ones Than Zeros

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to count the number of subarrays where the count of 1s is strictly greater than the count of 0s. A brute-force check of all O(N^2) subarrays would be too slow given N can be up to 10^5.

Solution

Count Subarrays With More Ones Than Zeros in Python

class Solution:
    def subarraysWithMoreZerosThanOnes(self, nums: List[int]) -> int:
        n = len(nums)
        MOD = 10**9 + 7
        
        # The range of prefix sums is [-n, n].
        # We use an offset to map these to positive indices for the BIT.
        # The size of the BIT needs to be 2*n + 2.
        # Indices will be in [1, 2*n + 1].
        size = 2 * n + 2
        bit = [0] * size
        OFFSET = n + 1

        def update(index, val):
            while index < size:
                bit[index] += val
                index += index & -index

        def query(index):
            s = 0
            while index > 0:
                s += bit[index]
                index -= index & -index
            return s

        total_count = 0
        prefix_sum = 0
        
        # Account for the empty prefix sum of 0.
        update(prefix_sum + OFFSET, 1)
        
        for num in nums:
            # Transform 0 to -1, 1 to 1 and update prefix sum.
            if num == 1:
                prefix_sum += 1
            else:
                prefix_sum -= 1
            
            # We need to find the number of previous prefix sums `p`
            # such that p < current prefix_sum. This is equivalent to `p <= prefix_sum - 1`.
            # We query the BIT for cumulative frequencies up to `prefix_sum - 1`.
            count_smaller = query(prefix_sum - 1 + OFFSET)
            
            total_count = (total_count + count_smaller) % MOD
            
            # Update the BIT with the current prefix sum.
            update(prefix_sum + OFFSET, 1)
            
        return total_count

Count Subarrays With More Ones Than Zeros in Java

class Solution {
    private static final int MOD = 1_000_000_007;
    private int[] bit;
    private int size;

    private void update(int index, int val) {
        for (; index < size; index += index & -index) {
            bit[index] += val;
        }
    }

    private int query(int index) {
        int sum = 0;
        for (; index > 0; index -= index & -index) {
            sum += bit[index];
        }
        return sum;
    }

    public int subarraysWithMoreZerosThanOnes(int[] nums) {
        int n = nums.length;
        // The range of prefix sums is [-n, n].
        // We use an offset to map these to positive indices for the BIT.
        // The size of the BIT needs to be 2*n + 2.
        // Indices will be in [1, 2*n + 1].
        this.size = 2 * n + 2;
        this.bit = new int[size];
        final int OFFSET = n + 1;

        long totalCount = 0;
        int prefixSum = 0;

        // Account for the empty prefix sum of 0.
        update(prefixSum + OFFSET, 1);

        for (int num : nums) {
            // Transform 0 to -1, 1 to 1 and update prefix sum.
            if (num == 1) {
                prefixSum++;
            } else {
                prefixSum--;
            }

            // We need to find the number of previous prefix sums `p`
            // such that p < current prefix_sum. This is equivalent to `p <= prefix_sum - 1`.
            // We query the BIT for cumulative frequencies up to `prefix_sum - 1`.
            int countSmaller = query(prefixSum - 1 + OFFSET);
            
            totalCount = (totalCount + countSmaller) % MOD;

            // Update the BIT with the current prefix sum.
            update(prefixSum + OFFSET, 1);
        }

        return (int) totalCount;
    }
}

Count Subarrays With More Ones Than Zeros in C++

class Solution {
public:
    int subarraysWithMoreZerosThanOnes(vector<int>& nums) {
        int n = nums.size();
        const int MOD = 1e9 + 7;
        const int OFFSET = n + 1;
        vector<int> bit(2 * n + 2, 0);

        auto update = [&](int index, int val) {
            for (; index < bit.size(); index += index & -index) {
                bit[index] += val;
            }
        };

        auto query = [&](int index) {
            int sum = 0;
            for (; index > 0; index -= index & -index) {
                sum += bit[index];
            }
            return sum;
        };

        long long total_count = 0;
        int prefix_sum = 0;

        // Account for the empty prefix sum of 0.
        update(prefix_sum + OFFSET, 1);

        for (int num : nums) {
            // Transform 0 to -1, 1 to 1 and update prefix sum.
            if (num == 1) {
                prefix_sum++;
            } else {
                prefix_sum--;
            }

            // We need to find the number of previous prefix sums `p`
            // such that p < current prefix_sum. This is equivalent to `p <= prefix_sum - 1`.
            // We query the BIT for cumulative frequencies up to `prefix_sum - 1`.
            int count_smaller = query(prefix_sum - 1 + OFFSET);
            
            total_count = (total_count + count_smaller) % MOD;

            // Update the BIT with the current prefix sum.
            update(prefix_sum + OFFSET, 1);
        }

        return total_count;
    }
};

Count Subarrays With More Ones Than Zeros in TypeScript

function subarraysWithMoreZerosThanOnes(nums: number[]): number {
    const n = nums.length;
    const MOD = 10**9 + 7;

    // The range of prefix sums is [-n, n].
    // We use an offset to map these to positive indices for the BIT.
    // The size of the BIT needs to be 2*n + 2.
    // Indices will be in [1, 2*n + 1].
    const size = 2 * n + 2;
    const bit: number[] = new Array(size).fill(0);
    const OFFSET = n + 1;

    function update(index: number, val: number): void {
        for (; index < size; index += index & -index) {
            bit[index] += val;
        }
    }

    function query(index: number): number {
        let sum = 0;
        for (; index > 0; index -= index & -index) {
            sum += bit[index];
        }
        return sum;
    }

    let totalCount = 0;
    let prefixSum = 0;

    // Account for the empty prefix sum of 0.
    update(prefixSum + OFFSET, 1);

    for (const num of nums) {
        // Transform 0 to -1, 1 to 1 and update prefix sum.
        if (num === 1) {
            prefixSum++;
        } else {
            prefixSum--;
        }

        // We need to find the number of previous prefix sums `p`
        // such that p < current prefix_sum. This is equivalent to `p <= prefix_sum - 1`.
        // We query the BIT for cumulative frequencies up to `prefix_sum - 1`.
        const countSmaller = query(prefixSum - 1 + OFFSET);
        
        totalCount = (totalCount + countSmaller) % MOD;

        // Update the BIT with the current prefix sum.
        update(prefixSum + OFFSET, 1);
    }

    return totalCount;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.