Given an integer array nums
and an integer k
, return the number of good subarrays of nums
.
A subarray arr
is good if there are at least k
pairs of indices (i, j)
such that i < j
and arr[i] == arr[j]
.
A subarray is a contiguous non-empty sequence of elements within an array.
For example:
Input: nums = [1,1,1,1,1]
, k = 10
Output: 1
Explanation: The only good subarray is the array nums itself.
Input: nums = [3,1,4,3,2,2,4]
, k = 2
Output: 4
Explanation: There are 4 different good subarrays:
[3,1,4,3,2,2]
that has 2 pairs.[3,1,4,3,2,2,4]
that has 3 pairs.[1,4,3,2,2,4]
that has 2 pairs.[4,3,2,2,4]
that has 2 pairs.def count_good_subarrays(nums, k):
n = len(nums)
count = 0
for i in range(n):
for j in range(i, n):
subarray = nums[i:j+1]
pairs = 0
for x in range(len(subarray)):
for y in range(x + 1, len(subarray)):
if subarray[x] == subarray[y]:
pairs += 1
if pairs >= k:
count += 1
return count
# Example usage:
nums1 = [1, 1, 1, 1, 1]
k1 = 10
print(f"Input: nums = {nums1}, k = {k1}\nOutput: {count_good_subarrays(nums1, k1)}")
nums2 = [3, 1, 4, 3, 2, 2, 4]
k2 = 2
print(f"Input: nums = {nums2}, k = {k2}\nOutput: {count_good_subarrays(nums2, k2)}")
count_good_subarrays(nums, k)
Function:
nums
and an integer k
as input.count
variable to 0, which will store the number of good subarrays.i = 0
and goes up to n-1
.j = i
and goes up to n-1
.nums[i:j+1]
is considered.pairs
variable to 0.(x, y)
such that x < y
.subarray[x] == subarray[y]
, it increments the pairs
count.pairs >= k
. If it is, it means the subarray is good, so the count
variable is incremented.count
.Example Usage:
The time complexity of the count_good_subarrays
function can be analyzed as follows:
n
times.n - i
times, which is O(n)
in the worst case.m
times, where m
is the length of the subarray. In the worst case, m
can be equal to n
. The number of iterations will be ( m * (m - 1) / 2 ), which is ( O(m^2) ). Therefore, it's (O(n^2)) in the worst case.So, the overall time complexity is ( O(n * n * n^2) = O(n^4) ). This is because for each of the ( O(n^2) ) subarrays, we iterate ( O(n^2) ) to calculate the number of pairs.
The space complexity of the count_good_subarrays
function is ( O(n) ) in the worst case, due to the space used by the subarray
variable, which can have a maximum length of n
. The other variables used (count
, pairs
, i
, j
, x
, y
) take up constant space, so they do not affect the overall space complexity.