To efficiently solve this problem, we need to handle two types of operations:
- Add Operations (
("add", x)): Append an integer to an array.
- Freq Queries (
("freq", k)): Compute the number of distinct subarrays in the current array where at least one element appears exactly k times.
🧠 Core Idea:
Rather than recalculating everything from scratch on each query (too slow!), we incrementally update our data structures as elements are added, and use a hashmap + sliding window technique to process "freq" efficiently.
We will use the following approach:
- For a given
k, we want to count the number of subarrays where any number appears exactly k times.
- Use a sliding window approach where for each starting index
i, expand the window as far as possible while tracking frequencies inside that window.
- Use a hashmap to maintain element counts, and a set to keep track of how many elements appear exactly
k times.
🛠 Efficient Strategy:
As we can’t process every subarray naively (~n²), we:
- Use a two pointer / sliding window approach.
- For each
freq(k) query, we process the current array using the optimized method described below.
✅ Implementation Details:
from collections import defaultdict
def process_queries(nums, queries):
result = []
arr = nums[:]
for query in queries:
if query[0] == "add":
arr.append(query[1])
elif query[0] == "freq":
k = query[1]
result.append(count_subarrays_with_exactly_k(arr, k))
return result
def count_subarrays_with_exactly_k(arr, k):
"""
Counts the number of subarrays where at least one number appears exactly k times.
"""
n = len(arr)
freq = defaultdict(int)
count_k = 0
total = 0
left = 0
count_of_elements_with_k = 0
freq_count = defaultdict(int) # number -> how many times it appears in freq
for right in range(n):
num = arr[right]
# Update frequencies
old_freq = freq[num]
freq[num] += 1
freq_count[old_freq] -= 1
freq_count[freq[num]] += 1
# If it reached exactly k, we now have a new valid number
if freq[num] == k:
count_of_elements_with_k += 1
# If it passed k (i.e., was k before), we lost that match
elif freq[num] == k + 1:
count_of_elements_with_k -= 1
while left <= right and count_of_elements_with_k > 0:
# all subarrays starting from current `left` to `right` are good
# Example: [left, right], [left+1, right], ..., [right, right]
total += n - right # All those subarrays will include [left:right+1]
# Shrink window from left
old_num = arr[left]
old_freq = freq[old_num]
freq[old_num] -= 1
# Update freq_count
freq_count[old_freq] -= 1
freq_count[old_freq - 1] += 1
if old_freq == k:
count_of_elements_with_k -= 1
elif old_freq - 1 == k:
count_of_elements_with_k += 1
left += 1
return total
📈 Time and Space Complexity:
- Per query:
- For
add → O(1)
- For
freq(k) → O(n) using sliding window (worst-case O(n) even amortized)
- Total complexity:
O(q * n) where q is the number of freq queries.
🔍 Example:
nums = [1, 2]
queries = [("freq", 1), ("add", 1), ("freq", 2)]
# Initial array: [1, 2]
# Subarrays:
# [1] → 1 appears once → valid
# [2] → 2 appears once → valid
# [1,2] → 1,2 appear once → valid
# So 3 valid for k=1
# After add 1: [1, 2, 1]
# Subarrays:
# check which subarrays have any number exactly 2 times
# [1] → invalid
# [2] → invalid
# [1,2] → all appear once → invalid
# [2,1] → still each once → invalid
# [1,2,1] → 1 appears 2 times → valid
# [1,2], [2,1], [1,2,1] — only [1,2,1] is valid
# Expected: [3, 1]
Test it:
print(process_queries([1, 2], [("freq", 1), ("add", 1), ("freq", 2)]))
# Output: [3, 1]
Let me know if you want to optimize further using memoization or caching repeated freq(k) calls.