Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Hashing & Two Pointers

Subarrays with Equal 0s, 1s and 2s

Hard · Hashing & Two Pointers · Asked at Amazon, Microsoft, Directi

The array contains only 0, 1 and 2. Print how many contiguous subarrays contain the same number of 0s, 1s and 2s.

Input

First line: n. Second line: n space-separated integers.

Output

The number of such subarrays.

Constraints

Keep running counts c0, c1, c2. A subarray (i, j] is balanced exactly when the pair (c1 − c0, c2 − c1) is the same at i and j. Count equal pairs with a hash map, starting from (0, 0) for the empty prefix.

Example 1

Input

7
0 1 0 2 0 1 0

Output

2

Example 2

Input

6
0 1 2 0 1 2

Output

5

Hints

  1. With one value pair (like 0s and 1s) you track a single difference of prefix counts.
  2. With three values you need two differences: c1 − c0 and c2 − c1.
  3. Two prefixes with the same pair of differences enclose a balanced subarray.

Approach

Walk the array keeping prefix counts c0, c1, c2. A subarray between prefixes i and j is balanced exactly when all three counts grew by the same amount — i.e. the pair (c1 − c0, c2 − c1) is equal at i and j. Store how many times each pair has occurred (starting with (0, 0) once for the empty prefix); at each step add the number of earlier prefixes with the same pair. The total can pass 2^31.

Complexity: O(n) expected time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    map<pair<int, int>, long long> seen;
    seen[{0, 0}] = 1;
    int c[3] = {0, 0, 0};
    long long count = 0;
    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;
        c[x]++;
        pair<int, int> key = {c[1] - c[0], c[2] - c[1]};
        count += seen[key]++;
    }
    cout << count << "\n";
    return 0;
}

Python solution

import sys

data = list(map(int, sys.stdin.read().split()))
n = data[0]
seen = {(0, 0): 1}
c = [0, 0, 0]
count = 0
for x in data[1 : 1 + n]:
    c[x] += 1
    key = (c[1] - c[0], c[2] - c[1])
    k = seen.get(key, 0)
    count += k
    seen[key] = k + 1
print(count)

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        HashMap<Long, Long> seen = new HashMap<>();
        long offset = 200001;
        seen.put(0L * offset + 0, 1L);
        int[] c = new int[3];
        long count = 0;
        for (int i = 0; i < n; i++) {
            in.nextToken();
            c[(int) in.nval]++;
            long key = (long) (c[1] - c[0]) * offset * 2 + (c[2] - c[1]);
            long k = seen.getOrDefault(key, 0L);
            count += k;
            seen.put(key, k + 1);
        }
        System.out.println(count);
    }
}

Solve Subarrays with Equal 0s, 1s and 2s online · All practice problems