Efficient Subarray Frequency Queries
Problem Statement
Process a series of queries on an array of integers. Queries can either add an integer to the end of the array or return the number of distinct subarrays where at least one number appears exactly k times.
Solution
We will use a combination of a frequency map, a hash map to store the subarrays, and a sliding window approach to efficiently process the queries.
from collections import defaultdict
class SubarrayFrequencyQueries:
def __init__(self):
self.nums = []
self.freq_map = defaultdict(int)
self.subarray_count = defaultdict(int)
self.distinct_subarrays = 0
def process_queries(self, queries):
results = []
for query in queries:
if query[0] == "add":
self.add(query[1])
else:
results.append(self.freq(query[1]))
return results
def add(self, x):
self.nums.append(x)
self.freq_map[x] += 1
self.update_subarray_count()
def freq(self, k):
return self.subarray_count[k]
def update_subarray_count(self):
self.subarray_count.clear()
self.distinct_subarrays = 0
count_map = defaultdict(int)
left = 0
for right in range(len(self.nums)):
count_map[self.nums[right]] += 1
while max(count_map.values()) > 1:
count_map[self.nums[left]] -= 1
if count_map[self.nums[left]] == 0:
del count_map[self.nums[left]]
left += 1
freqs = tuple(sorted(count_map.values()))
self.subarray_count[freqs] += 1
self.distinct_subarrays += 1 - self.subarray_count[freqs]
# Manually update self.subarray_count for k=1 to len(self.nums)
for k in range(1, len(self.nums) + 1):
if k in [v for v in count_map.values()]:
self.subarray_count[k] = self.distinct_subarrays
# However, the solution above still has room for improvement.
# Here is a more optimized solution.
class SubarrayFrequencyQueries:
def __init__(self):
self.nums = []
self.count_map = defaultdict(int)
self.freq_map = defaultdict(int)
def process_queries(self, queries):
results = []
for query in queries:
if query[0] == "add":
self.add(query[1])
else:
results.append(self.freq(query[1]))
return results
def add(self, x):
self.nums.append(x)
self.count_map[x] += 1
def freq(self, k):
res = 0
window_counts = defaultdict(int)
window_counts[0] = 1
prefix_sum = 0
for count in self.count_map.values():
if count > k:
prefix_sum += 1
window_counts[prefix_sum] += 1
for key in list(window_counts.keys()):
if key >= 1:
window_counts[key] -= window_counts[key - 1]
return window_counts[k]
# Example usage:
sfq = SubarrayFrequencyQueries()
sfq.nums = [1, 2, 3]
sfq.count_map = {1: 1, 2: 1, 3: 1}
queries = [("freq", 1), ("add", 4), ("freq", 1), ("freq", 2)]
print(sfq.process_queries(queries))
Explanation
- The provided solution defines a class
SubarrayFrequencyQueries to process queries efficiently.
- It maintains a frequency map
count_map to store the frequency of each number in the current array.
- For the "freq" query, it calculates the number of distinct subarrays where at least one number appears exactly k times.
- The solution utilizes a sliding window approach and hash maps to achieve efficient query processing.
Time Complexity
- The time complexity of adding an element to the array is O(1).
- The time complexity of the "freq" query is O(n), where n is the length of the current array.
Space Complexity
- The space complexity is O(n), where n is the length of the current array. This is due to the storage required for the frequency map and other data structures.