Skip to content

2031. Count Subarrays With More Ones Than Zeros 👍

  • Time: $O(n\log n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class FenwickTree {
 public:
  FenwickTree(int n) : n(n), sums(2 * n + 1) {}

  void update(int i, int delta) {
    i += n + 1;  // Re-mapping
    while (i < sums.size()) {
      sums[i] += delta;
      i += i & -i;
    }
  }

  int get(int i) {
    i += n + 1;  // Re-mapping
    int sum = 0;
    while (i > 0) {
      sum += sums[i];
      i -= i & -i;
    }
    return sum;
  }

 private:
  const int n;
  vector<int> sums;
};

class Solution {
 public:
  int subarraysWithMoreZerosThanOnes(vector<int>& nums) {
    constexpr int kMod = 1'000'000'007;
    int ans = 0;
    int prefix = 0;
    FenwickTree tree(nums.size());
    tree.update(0, 1);

    for (const int num : nums) {
      prefix += num == 0 ? -1 : 1;
      ans += tree.get(prefix - 1);
      ans %= kMod;
      tree.update(prefix, 1);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class FenwickTree {
  public FenwickTree(int n) {
    this.n = n;
    sums = new int[2 * n + 1];
  }

  public void update(int i, int delta) {
    i += n + 1; // Re-mapping
    while (i < sums.length) {
      sums[i] += delta;
      i += i & -i;
    }
  }

  public int get(int i) {
    i += n + 1; // Re-mapping
    int sum = 0;
    while (i > 0) {
      sum += sums[i];
      i -= i & -i;
    }
    return sum;
  }

  private int n;
  private int[] sums;
}

class Solution {
  public int subarraysWithMoreZerosThanOnes(int[] nums) {
    final int kMod = 1_000_000_007;
    int ans = 0;
    int prefix = 0;
    FenwickTree tree = new FenwickTree(nums.length);
    tree.update(0, 1);

    for (final int num : nums) {
      prefix += num == 0 ? -1 : 1;
      ans += tree.get(prefix - 1);
      ans %= kMod;
      tree.update(prefix, 1);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class FenwichTree:
  def __init__(self, n: int):
    self.n = n
    self.sums = [0] * (2 * n + 1)

  def update(self, i: int, delta: int) -> None:
    i += self.n + 1  # Re-mapping
    while i < len(self.sums):
      self.sums[i] += delta
      i += i & -i

  def get(self, i: int) -> int:
    i += self.n + 1  # Re-mapping
    summ = 0
    while i > 0:
      summ += self.sums[i]
      i -= i & -i
    return summ


class Solution:
  def subarraysWithMoreZerosThanOnes(self, nums: List[int]) -> int:
    kMod = 1_000_000_007
    ans = 0
    prefix = 0
    tree = FenwichTree(len(nums))
    tree.update(0, 1)

    for num in nums:
      prefix += -1 if num == 0 else 1
      ans += tree.get(prefix - 1)
      ans %= kMod
      tree.update(prefix, 1)

    return ans