We need to solve: find number of subarrays with average equal to k. Given array nums and integer k? It says average equal to a given value k. Usually k might be integer? But average could be fractional. The input likely: nums is array of integers, k is integer? But average could be non-integer. If k is given as integer, we can multiply both sides: sum(subarray)/len = k => sum = k * len. So we want subarrays where sum = k * length. That's a condition. But if k is not integer? The problem statement says "given value k", and "average equal to a given value k". Could be any number. Usually in coding problems, k is integer, and we find subarrays with average exactly k. But if k is a floating point, we might need to handle differently. But given that nums are integers, the average can be a rational. But it's easier to treat k as integer. Let's assume k is integer. However, we can handle general real numbers by considering sum - klength = 0. But careful with floating point precision. Better to multiply by denominator if k is fraction. But typical LeetCode problem: Number of Subarrays with Average Equal to K? Actually I recall a problem: "Number of Subarrays with Average Greater than or Equal to K" or "Number of Subarrays with Given Average". There is a known trick: transform array: for each element, compute prefix sum. Let prefix sum array P: P[i] = sum of nums[0..i-1]. Then for a subarray from i to j-1 (length L=j-i), average = (P[j]-P[i])/(j-i) = k => P[j]-P[i] = k(j-i) => (P[j] - kj) = (P[i] - ki). So define new array B[i] = P[i] - ki. Then we need number of pairs i<j such that B[j] == B[i]. Also subarray of length zero? i=j not allowed because length zero not considered. So we count frequency of each B value, and for each value with count c, the number of subarrays is c choose 2 = c(c-1)/2. Also note that we need to include the prefix at index 0: P[0]=0, so B[0] = 0 - k*0 = 0. So we include that.
Thus algorithm: compute prefix sum, compute B values, use hashmap to count frequencies. Then sum over frequencies.
Complexities: O(n) time, O(n) space.
Edge cases: k might be float? But then we need to avoid floating point: if k is rational we can use integer arithmetic by scaling. But if k is float, we can treat as double and use hash of doubles? But double hash may have precision issues. However, typical problem: k is integer. So implement for integer k. We'll note that if k is not integer, we can treat it as double and do the same transformation, but careful with equality.
Better: Let's assume k is integer. We'll state that.
Alternatively, we can treat as given value k (could be double). We'll note that we can convert to integer by multiplying by something? But maybe the problem expects to handle integer k.
Let's check: The problem says "average equal to a given value k". Usually average is a rational. But if nums are integers, sum is integer, length is integer, so average = sum/len. For this to equal k exactly, k must be rational. If k is integer, it's simpler. The known trick: prefix[i] - k*i.
Thus algorithm:
- Initialize a hashmap
count to store frequencies of transformed prefix values. Set B0 = 0, count[0] = 1.
- Initialize prefix_sum = 0.
- For i from 1 to n (or index j from 0 to n-1 with prefix after index):
- prefix_sum += nums[i] (or at each step we compute for prefix ending at i, i inclusive).
Compute transformed value: B = prefix_sum - k * (i+1) (since prefix_sum is sum up to index i inclusive, length = i+1). But if we have prefix sum up to index i (exclusive), then we handle differently.
Better: Use prefix array of size n+1: prefix[0]=0. For i from 1 to n: prefix[i] = prefix[i-1] + nums[i-1]. Then B[i] = prefix[i] - k*i. Then for i from 0 to n, count frequencies of B[i]. Then answer = sum over frequencies of (freq choose 2).
Yes.
Implementation in Python:
def numSubarrayAvg(nums, k):
from collections import defaultdict
count = defaultdict(int)
count[0] = 1 # B[0] = 0
prefix = 0
ans = 0
for i, num in enumerate(nums, start=1):
prefix += num
b = prefix - k * i
# before incrementing count[b], we can add current count to ans because any previous same B gives a valid subarray
ans += count[b]
count[b] += 1
return ans
That is O(n).
We need to explain algorithm: prefix transformation.
We'll also discuss if k is not integer: we can avoid floating point by using multiplication? Actually we can rearrange: sum = k * len => if k = p/q rational, then qsum = plen. That could be integer if p,q integers. So we can do transformation: qprefix - pi. But careful: k might be float not rational? Usually it's given as integer or rational. But we can note that the algorithm works for any real k if we use double, but precision may be issue. So for exact equality, it's best if k is integer or rational and we use integer arithmetic.
We'll explain using the transformation.
We also might need to handle negative numbers? Works fine.
Thus solution.
Now we need to output function and explanation.
Also maybe they want to count subarrays with average exactly k, not greater. So we'll implement.
Let's produce final answer.
Solution Overview
We are given an array nums of integers and a target average k.
We need to count the number of (contiguous) subarrays whose average equals k.
For a subarray nums[l … r] (inclusive) with length L = r-l+1:
average = (sum of elements) / L = k
=> sum = k * L
Let P[i] be the prefix sum up to (but not including) index i:
P[0] = 0
P[i] = nums[0] + nums[1] + … + nums[i-1] (1 ≤ i ≤ n)
For a subarray [l, r] we have sum = P[r+1] - P[l] and L = (r+1) - l.
Thus the condition becomes
P[r+1] - P[l] = k * ((r+1) - l)
=> (P[r+1] - k*(r+1)) = (P[l] - k*l)
Define a transformed prefix value:
B[i] = P[i] - k * i (0 ≤ i ≤ n)
Now a subarray [l, r] satisfies the average condition iff B[l] == B[r+1].
So the problem reduces to:
How many pairs of indices (i, j) with i < j have the same value B?
If a particular value v appears c times among the B array, it contributes
c choose 2 = c*(c-1)/2 valid subarrays (each pair of occurrences forms a subarray).
Algorithm
- Initialise a hash map
freq to count occurrences of B values.
freq[0] = 1 because B[0] = 0.
- Iterate
i from 1 to n:
- Update the running prefix sum:
prefix += nums[i-1].
- Compute
b = prefix - k * i.
- The current
b already occurred freq[b] times; each prior occurrence yields a new subarray ending at i-1. Add freq[b] to the answer.
- Increment
freq[b].
- Return the accumulated answer.
Complexity Analysis
- Time:
O(n) – one pass over the array, each operation is O(1) on average.
- Space:
O(n) – the hash map may store up to n+1 distinct B values.
Handling Non‑Integer k
The derivation uses exact equality. For integer k the transformed value B is an integer, guaranteeing exact comparison with a hash map.
If k is a rational number p/q (in lowest terms), we can multiply the equation by q to avoid fractions:
q * (P[j] - P[i]) = p * (j - i)
=> (q*P[j] - p*j) = (q*P[i] - p*i)
Thus we compute B[i] = q * P[i] - p * i (still integers).
If k is an arbitrary floating‑point value, using doubles may introduce precision errors; it is safer to treat it as a rational if possible.
Reference Implementation (Python)
from collections import defaultdict
from typing import List
def count_subarrays_with_average(nums: List[int], k: int) -> int:
"""
Returns the number of contiguous subarrays of `nums` whose average equals `k`.
Parameters:
- nums: list of integers.
- k: integer target average.
The algorithm uses prefix sums and a hash map to count equal transformed values.
"""
freq = defaultdict(int)
freq[0] = 1 # B[0] = 0
prefix = 0
ans = 0
for i, num in enumerate(nums, start=1): # i is the length of prefix (i.e., index in B)
prefix += num
b = prefix - k * i
ans += freq[b] # each previous occurrence pairs with current index
freq[b] += 1
return ans
# Example usage:
# print(count_subarrays_with_average([1, 2, 3, 4], 2)) # Output depends on input
Explanation of the Code
freq stores how many times each transformed prefix b = prefix - k*i has been seen.
ans accumulates counts: for each new b, the number of previously seen identical bs is exactly the number of subarrays ending at the current position that satisfy the average condition.
- The loop index
i starts at 1 because i represents the number of elements processed (the prefix length). The corresponding B index is i, matching the derivation with P[i].
This solution efficiently counts the desired subarrays in linear time.