Getting everything ready for you…

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

0s

Practice › Sliding Window

Count Nice Subarrays

Medium · Sliding Window · Asked at Amazon, Microsoft, Roblox

A subarray is nice if it contains exactly k odd numbers. Count the nice subarrays.

Input

First line: n k. Second line: n integers.

Output

The number of nice subarrays.

Constraints

exactly(k) = atMost(k) − atMost(k − 1), and atMost(k) is a classic sliding-window count.

Example 1

Input

5 3
1 1 2 1 1

Output

2

Example 2

Input

3 1
2 4 6

Output

0

Hints

  1. Only odd/even matters: map each value to 1 if odd, 0 if even. Now count subarrays with sum exactly k.
  2. exactly(k) = atMost(k) − atMost(k − 1). atMost(k) counts, for each right end, how many left ends keep the window at ≤ k odd numbers.

Approach

atMost(k): slide a window, adding a[r] % 2; while the number of odds exceeds k, move l. Every left end from l to r gives a valid subarray ending at r, so add r − l + 1. The answer is atMost(k) − atMost(k − 1). (A prefix-count hash map also works, as in "subarray sum equals K".)

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

Solution

C++ solution

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

long long atMost(const vector<int> &a, int k) {
    if (k < 0) return 0;
    long long res = 0;
    int l = 0, odd = 0;
    for (int r = 0; r < (int)a.size(); r++) {
        odd += a[r] % 2;
        while (odd > k) odd -= a[l++] % 2;
        res += r - l + 1;
    }
    return res;
}

int main() {
    int n, k;
    cin >> n >> k;
    vector<int> a(n);
    for (auto &x : a) cin >> x;
    cout << atMost(a, k) - atMost(a, k - 1) << "\n";
    return 0;
}

Python solution

import sys


def at_most(a, k):
    if k < 0:
        return 0
    res = l = odd = 0
    for r, x in enumerate(a):
        odd += x % 2
        while odd > k:
            odd -= a[l] % 2
            l += 1
        res += r - l + 1
    return res


data = list(map(int, sys.stdin.read().split()))
n, k, a = data[0], data[1], data[2:]
print(at_most(a, k) - at_most(a, k - 1))

Java solution

import java.util.*;

public class Main {
    static long atMost(int[] a, int k) {
        if (k < 0) return 0;
        long res = 0;
        int l = 0, odd = 0;
        for (int r = 0; r < a.length; r++) {
            odd += a[r] % 2;
            while (odd > k) odd -= a[l++] % 2;
            res += r - l + 1;
        }
        return res;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(), k = sc.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = sc.nextInt();
        System.out.println(atMost(a, k) - atMost(a, k - 1));
    }
}

Solve Count Nice Subarrays online · All practice problems