Count Number of Nice Subarrays

Medium Arrays & Hashing Sliding Window · Variable

Count Number of Nice Subarrays is a medium arrays & hashing problem solved with the sliding window · variable pattern. The best approach, optimal (sliding window, at most k minus at most k - 1), runs in O(n) time and O(1) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (every start, extend to the right) up.

Problem

You are given an array of positive integers nums and an integer k.

Call a contiguous, non-empty subarray nice if it contains exactly k odd numbers. The even numbers inside it can be any in number.

Return how many nice subarrays nums has. Two subarrays count separately when they start or end at different indexes, even if they hold the same values.

Examples

Example 1

Input
nums = [1,1,2,1,1], k = 3
Output
2
Why
Only two stretches hold exactly three odd numbers: [1,1,2,1] (indexes 0 to 3) and [1,2,1,1] (indexes 1 to 4). The whole array holds four odd numbers, which is too many.

Example 2

Input
nums = [2,4,6], k = 1
Output
0
Why
Every number is even, so no subarray holds even one odd number.

Example 3

Input
nums = [2,2,2,1,2,2,1,2,2,2], k = 2
Output
16
Why
A nice subarray must contain both 1s (indexes 3 and 6). It may start at any of indexes 0 to 3 and end at any of indexes 6 to 9, giving 4 × 4 = 16 choices.

Constraints

  • 1 <= nums.length <= 5 * 10^4
  • 1 <= nums[i] <= 10^5
  • 1 <= k <= nums.length

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 15 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (every start, extend to the right)O(n^2)O(1)
Prefix counts of odd numbersO(n)O(n)
Optimal (sliding window, at most k minus at most k - 1)O(n)O(1)

1Brute force (every start, extend to the right)

TimeO(n^2)There are n starts, and each can extend over up to n ends.
SpaceO(1)Only a few counters.

Fix where the subarray starts. Walk the end to the right, keeping a running count of odd numbers. Each time the count equals k, that subarray is nice. Once the count passes k it can never come back down, so stop and move to the next start.

  1. For each start i: set odd = 0.
  2. For each end j from i: if nums[j] is odd, add one to odd.
  3. If odd == k, add one to the answer. If odd > k, break: longer subarrays only have more odd numbers.
  4. Return the answer.
class Solution {
    public int numberOfSubarrays(int[] nums, int k) {
        int n = nums.length, count = 0;
        for (int i = 0; i < n; i++) {
            int odd = 0;
            for (int j = i; j < n; j++) {
                if (nums[j] % 2 == 1) odd++;
                if (odd == k) count++;
                else if (odd > k) break;
            }
        }
        return count;
    }
}

2Prefix counts of odd numbers

TimeO(n)One pass, with constant work per number.
SpaceO(n)The table of running counts has n + 1 slots.

Keep a running count of odd numbers seen so far. A subarray that ends here has exactly k odd numbers when it starts right after a point where the running count was k less than it is now. So remember how many times each running count has appeared (starting with count 0 once, for the empty prefix), and for each new number add how many times the count odd - k has appeared.

  1. seen is an array of size n + 1, with seen[0] = 1 for the empty prefix. odd = 0, count = 0.
  2. For each number: if it is odd, add one to odd.
  3. If odd >= k, add seen[odd - k] to count: each of those earlier points is a start that leaves exactly k odd numbers.
  4. Add one to seen[odd]. Return count.
class Solution {
    public int numberOfSubarrays(int[] nums, int k) {
        int[] seen = new int[nums.length + 1];
        seen[0] = 1;
        int odd = 0, count = 0;
        for (int x : nums) {
            if (x % 2 == 1) odd++;
            if (odd >= k) count += seen[odd - k];
            seen[odd]++;
        }
        return count;
    }
}

3Optimal (sliding window, at most k minus at most k - 1)

TimeO(n)Each call moves right across the array once and left at most once, and there are two calls.
SpaceO(1)Only the two pointers and counters.

Counting windows with exactly k odd numbers is awkward with two pointers, because a window can be extended by even numbers on either side without changing its count. Counting windows with at most k odd numbers is easy: grow the right end, shrink the left end until the window has at most k odd numbers, and then every start from left to right is valid for this end. The windows with exactly k odd numbers are the ones with at most k, minus the ones with at most k - 1.

  1. atMost(m): left = 0, odd = 0, total = 0.
  2. For each right: if nums[right] is odd, add one to odd. While odd > m, remove nums[left] from the window (subtract one if it is odd) and move left forward.
  3. Every start from left to right gives a valid window ending at right: add right - left + 1 to total.
  4. Return atMost(k) - atMost(k - 1).
class Solution {
    public int numberOfSubarrays(int[] nums, int k) {
        return atMost(nums, k) - atMost(nums, k - 1);
    }

    private int atMost(int[] nums, int m) {
        int left = 0, odd = 0, total = 0;
        for (int right = 0; right < nums.length; right++) {
            if (nums[right] % 2 == 1) odd++;
            while (odd > m) {
                if (nums[left] % 2 == 1) odd--;
                left++;
            }
            total += right - left + 1;
        }
        return total;
    }
}

Edge cases to test

  • No odd numbers at all, or fewer than k of them (answer 0)
  • Every number is odd: each window of exactly k numbers is the only kind of nice subarray, so the answer is n - k + 1
  • A single element: the answer is 1 if it is odd and k = 1, otherwise 0
  • Long runs of even numbers on both sides of a group of k odd numbers multiply the count
  • k equals the number of odd numbers in the whole array
  • Only parity matters: 7 and 1 behave the same, and so do 2 and 100000

Hints

Hint 1

Only whether a number is odd matters. Replace each number with 1 if it is odd and 0 if it is even. Now you are counting subarrays whose sum is exactly k.

Hint 2

Let odd(i) be the number of odd values among the first i numbers. The subarray from a to b has odd(b + 1) - odd(a) odd values. For each end, how many earlier prefixes have the right count?

Hint 3

Counting windows with at most k odd numbers is easy with two pointers: for each right end, every start from left to right works. Exactly k is at most k minus at most k - 1.

FAQ

What is the best time complexity for Count Number of Nice Subarrays?

Optimal (sliding window, at most k minus at most k - 1) runs in O(n) time and O(1) extra space. Each call moves right across the array once and left at most once, and there are two calls.

Which pattern does Count Number of Nice Subarrays use?

It is a arrays & hashing problem that uses the sliding window · variable pattern. Other problems with the same pattern: Minimum Size Subarray Sum, Count of Subarrays with Product Less Than K, Longest Repeating Character Replacement.

Is there a brute force solution for Count Number of Nice Subarrays?

Yes. Brute force (every start, extend to the right) takes O(n^2) time and O(1) space. Fix where the subarray starts.

Which edge cases should I test for Count Number of Nice Subarrays?

No odd numbers at all, or fewer than k of them (answer 0); Every number is odd: each window of exactly k numbers is the only kind of nice subarray, so the answer is n - k + 1; A single element: the answer is 1 if it is odd and k = 1, otherwise 0; Long runs of even numbers on both sides of a group of k odd numbers multiply the count; k equals the number of odd numbers in the whole array; Only parity matters: 7 and 1 behave the same, and so do 2 and 100000.