Count the Number of Good Subarrays
Count the Number of Good Subarrays is a medium arrays & hashing problem solved with the sliding window · hash map pattern.
The best approach, optimal (sliding window with a pair count), runs in O(n) time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (every start, stop at the first good end) up.
Problem
You are given an integer array nums and an integer k.
A contiguous, non-empty subarray is good if it contains at least k pairs of indexes (i, j) with i < j and nums[i] == nums[j]. In other words, count every way to pick two different positions inside the subarray that hold the same value; the subarray is good when that count is k or more.
Return the number of good subarrays of nums. 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,1,1,1], k = 10- Output
1- Why
- Five equal numbers form 5 × 4 / 2 = 10 equal pairs, so the whole array is good. Any shorter subarray has at most four equal numbers and only 6 pairs, which is not enough.
Example 2
- Input
nums = [3,1,4,3,2,2,4], k = 2- Output
4- Why
- A good subarray needs two equal pairs. The good ones are indexes 0 to 5 (pairs 3,3 and 2,2), 0 to 6, 1 to 6 (pairs 4,4 and 2,2) and 2 to 6 (pairs 4,4 and 2,2). Every other subarray has at most one equal pair.
Example 3
- Input
nums = [2,2,2], k = 1- Output
3- Why
- Indexes 0 to 1 and 1 to 2 each hold one pair of 2s, and the whole array holds three pairs. The three single elements hold none.
Constraints
1 <= nums.length <= 10^51 <= nums[i] <= 10^91 <= k <= 10^9
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.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 16 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.
| Approach | Time | Space |
|---|---|---|
| Brute force (every start, stop at the first good end) | O(n^2) | O(n) |
| Optimal (sliding window with a pair count) | O(n) | O(n) |
1Brute force (every start, stop at the first good end)
O(n^2)There are n starts, and each can extend over up to n ends, with constant expected work per step in the hash map.O(n)The frequency map holds up to n different values.Fix where the subarray starts and grow it to the right, keeping a count of each value and the number of equal pairs. When a value that is already in the subarray c times is added, it forms c new pairs. The first time the pair count reaches k, this end and every later end give a good subarray, because adding numbers never removes pairs. So add all of them at once and move on to the next start.
- For each start i: an empty frequency map and pairs = 0.
- For each end j from i: let c be how many times nums[j] already appears. Add c to pairs, then add one to its count.
- If pairs >= k, the ends j, j + 1, ..., n - 1 all work: add n - j to the answer and stop extending this start.
- Return the answer.
class Solution {
public long countGood(int[] nums, int k) {
int n = nums.length;
long count = 0;
for (int i = 0; i < n; i++) {
Map<Integer, Integer> freq = new HashMap<>();
long pairs = 0;
for (int j = i; j < n; j++) {
int c = freq.getOrDefault(nums[j], 0);
pairs += c;
freq.put(nums[j], c + 1);
if (pairs >= k) {
count += n - j;
break;
}
}
}
return count;
}
}class Solution:
def countGood(self, nums: List[int], k: int) -> int:
n = len(nums)
count = 0
for i in range(n):
freq = {}
pairs = 0
for j in range(i, n):
c = freq.get(nums[j], 0)
pairs += c
freq[nums[j]] = c + 1
if pairs >= k:
count += n - j
break
return countclass Solution {
public:
long long countGood(vector<int>& nums, int k) {
int n = nums.size();
long long count = 0;
for (int i = 0; i < n; i++) {
unordered_map<int, int> freq;
long long pairs = 0;
for (int j = i; j < n; j++) {
int c = freq[nums[j]];
pairs += c;
freq[nums[j]] = c + 1;
if (pairs >= k) {
count += n - j;
break;
}
}
}
return count;
}
};function countGood(nums, k) {
const n = nums.length;
let count = 0;
for (let i = 0; i < n; i++) {
const freq = new Map();
let pairs = 0;
for (let j = i; j < n; j++) {
const c = freq.get(nums[j]) || 0;
pairs += c;
freq.set(nums[j], c + 1);
if (pairs >= k) {
count += n - j;
break;
}
}
}
return count;
}2Optimal (sliding window with a pair count)
O(n)right moves across the array once and left moves at most n times in total, each with constant expected work in the hash map.O(n)The frequency map holds up to n different values.Being good only gets easier as a subarray grows, so for each start there is a smallest good end, and that end never moves left when the start moves right. Keep one window from left to right with a frequency map and its pair count. Move right forward one step at a time. While the window is good, the start left works with this end and every later end, so add n - right; then remove nums[left] from the window and move left forward. Removing a value that appears c times (counting itself) takes away c - 1 pairs.
- freq is an empty map, left = 0, pairs = 0, count = 0.
- For each right: let c be the count of nums[right] so far. Add c to pairs and add one to its count.
- While pairs >= k: add n - right to count. Lower the count of nums[left] by one, subtract the new count from pairs, and move left forward.
- Return count.
class Solution {
public long countGood(int[] nums, int k) {
Map<Integer, Integer> freq = new HashMap<>();
int n = nums.length, left = 0;
long pairs = 0, count = 0;
for (int right = 0; right < n; right++) {
int c = freq.getOrDefault(nums[right], 0);
pairs += c;
freq.put(nums[right], c + 1);
while (pairs >= k) {
count += n - right;
int d = freq.get(nums[left]) - 1;
freq.put(nums[left], d);
pairs -= d;
left++;
}
}
return count;
}
}class Solution:
def countGood(self, nums: List[int], k: int) -> int:
freq = {}
n, left = len(nums), 0
pairs = count = 0
for right in range(n):
c = freq.get(nums[right], 0)
pairs += c
freq[nums[right]] = c + 1
while pairs >= k:
count += n - right
d = freq[nums[left]] - 1
freq[nums[left]] = d
pairs -= d
left += 1
return countclass Solution {
public:
long long countGood(vector<int>& nums, int k) {
unordered_map<int, int> freq;
int n = nums.size(), left = 0;
long long pairs = 0, count = 0;
for (int right = 0; right < n; right++) {
int c = freq[nums[right]];
pairs += c;
freq[nums[right]] = c + 1;
while (pairs >= k) {
count += n - right;
int d = freq[nums[left]] - 1;
freq[nums[left]] = d;
pairs -= d;
left++;
}
}
return count;
}
};function countGood(nums, k) {
const freq = new Map();
const n = nums.length;
let left = 0, pairs = 0, count = 0;
for (let right = 0; right < n; right++) {
const c = freq.get(nums[right]) || 0;
pairs += c;
freq.set(nums[right], c + 1);
while (pairs >= k) {
count += n - right;
const d = freq.get(nums[left]) - 1;
freq.set(nums[left], d);
pairs -= d;
left++;
}
}
return count;
}Edge cases to test
- All numbers distinct: no subarray has a single pair, so the answer is 0
- A single element: it has no pairs, so the answer is 0
- All numbers equal: a subarray of length L has L × (L - 1) / 2 pairs
- k larger than the number of pairs in the whole array (answer 0)
- k = 1: a subarray is good as soon as it holds any value twice
- The answer can reach about n × (n + 1) / 2, which is 5 × 10^9 for n = 10^5: it needs a 64-bit integer, and so does the running pair count
- Values go up to 10^9, so count them with a hash map, not an array indexed by value
Hints
Hint 1
When a value that has already appeared c times joins a subarray, how many new equal pairs does it create?
Hint 2
Adding a number to a subarray never removes pairs. So if the subarray from i to j is good, every longer subarray from i to j + 1, j + 2 and so on is good too.
Hint 3
Use two pointers. Move the right end forward, adding pairs. While the window from left to right is good, every end from right to n - 1 works for this left: add n - right, then drop nums[left] and move left forward.
FAQ
What is the best time complexity for Count the Number of Good Subarrays?
Optimal (sliding window with a pair count) runs in O(n) time and O(n) extra space. right moves across the array once and left moves at most n times in total, each with constant expected work in the hash map.
Which pattern does Count the Number of Good Subarrays use?
It is a arrays & hashing problem that uses the sliding window · hash map pattern. Other problems with the same pattern: Number of Substrings Containing All Three Characters, Minimum Window Substring, Longest Substring with At Most K Distinct Characters.
Is there a brute force solution for Count the Number of Good Subarrays?
Yes. Brute force (every start, stop at the first good end) takes O(n^2) time and O(n) space. Fix where the subarray starts and grow it to the right, keeping a count of each value and the number of equal pairs.
Which edge cases should I test for Count the Number of Good Subarrays?
All numbers distinct: no subarray has a single pair, so the answer is 0; A single element: it has no pairs, so the answer is 0; All numbers equal: a subarray of length L has L × (L - 1) / 2 pairs; k larger than the number of pairs in the whole array (answer 0); k = 1: a subarray is good as soon as it holds any value twice; The answer can reach about n × (n + 1) / 2, which is 5 × 10^9 for n = 10^5: it needs a 64-bit integer, and so does the running pair count; Values go up to 10^9, so count them with a hash map, not an array indexed by value.