Similar Problems

Similar Problems not available

Count Subarrays With More Ones Than Zeros - Leetcode Solution

Companies:

LeetCode:  Count Subarrays With More Ones Than Zeros Leetcode Solution

Difficulty: Medium

Topics: binary-search array  

Problem Statement:

Given an array of integers nums, return the number of subarrays with more 1's than 0's.

Solution:

We can solve this problem using a sliding window approach. We will maintain two pointers left and right which will define the boundaries of the subarray we are currently looking at. We will then count the number of 1's and 0's in this subarray and if the count of 1's is greater than the count of 0's, we will increment our answer.

Algorithm:

  1. Initialize left, right and answer to 0.
  2. Initialize count to 0.
  3. Traverse the array from left to right and do the following for each index i: a. If the value at i is 1, increment count. Else, decrement count. b. If count is greater than 0, update answer by adding the length of the subarray from left to i to our answer. c. If count becomes negative, reset count to 0 and move left pointer to i + 1.
  4. Return answer.

Code:

class Solution {
public:
    int subarraysWithMoreOnesThanZeroes(vector<int>& nums) {
        int left = 0, right = 0, count = 0, answer = 0, n = nums.size();
        while (right < n) {
            if (nums[right] == 1)
                count++;
            else
                count--;
            
            while (count < 0) {
                if (nums[left] == 1)
                    count--;
                else
                    count++;
                left++;
            }
            if (count > 0)
                answer += right - left + 1;
            right++;
        }
        return answer;
    }
};

Time Complexity: O(n) Space Complexity: O(1)

Explanation:

We use two pointers left and right to define our current subarray. We traverse the array from left to right and for each index we add 1 to our count if the value at the index is 1 and subtract 1 if the value is 0. If the count becomes negative, it means we have more 0's than 1's in the subarray between left and right, so we move the left pointer forward until we have more 1's than 0's. We increment our answer if there are more 1's than 0's in the subarray between left and right.

Count Subarrays With More Ones Than Zeros Solution Code

1