We need to process two types of queries on an array a[1..n] with values up to 1e5, n,m up to 1e5.
Query type 1: given l,r,k, we need to consider the multiset of values in subarray a[l..r]. For each distinct value x, let cnt_x be its frequency in that subarray. We need to choose k distinct values from the set of distinct values appearing in the subarray. For chosen values x_i, we have cnt_i = cnt_{x_i}. We require cnt_i > 0 (obviously). And we want to minimize the maximum difference between any two cnt_i values, i.e., dif = max(cnt_i) - min(cnt_i). Actually condition: |cnt_i - cnt_j| ≤ dif for all i,j, so dif must be at least (max cnt - min cnt). So we want to choose k distinct values such that the spread (max cnt - min cnt) is minimized. The answer is that minimal possible dif (or -1 if fewer than k distinct values exist in the subarray).
Note: we can choose any subset of distinct values of size k. We want to minimize the range (max cnt - min cnt) among the chosen counts.
This is reminiscent of: given a set of numbers (the frequencies of distinct elements in the subarray), we want to choose k of them to minimize the difference between the maximum and minimum. That's like we sort the frequencies and take a sliding window of length k, and compute min difference between the largest and smallest in that window. Indeed, if we have sorted list of frequencies, picking any k of them the min possible max-min is achieved by picking a contiguous block in sorted order (since sorted, any selection's max-min is at least the difference between the smallest and largest in that sorted set, and you can always take a contiguous block containing those min and max). Actually careful: given a set of numbers, the minimal range for selecting k numbers is found by sorting the numbers and taking the minimum of (value[i+k-1] - value[i]) over all i. Because any optimal set of k numbers, when sorted, its min and max are some values. Among all sets, the minimal max-min is achieved by a contiguous block in sorted order: if you have k numbers not contiguous, you can adjust to reduce range? Classic problem: Given an array, find k elements that minimize the difference between max and min. The solution: sort, then sliding window. Yes.
Thus for query type 1: we need to list the frequencies of all distinct elements in the subarray, then sort them, then if the number of distinct values D < k, answer -1; else answer min over i of (sorted_freq[i+k-1] - sorted_freq[i]).
So the core problem is: dynamic array with point updates (values changed), and we need to answer range queries that ask for the minimal difference between the k-th smallest frequencies after sorting the frequencies of distinct values in the range.
But note: frequencies are per value in the range. The distinct values are up to 1e5, and n up to 1e5. We need to process many queries (m up to 1e5). So we need something efficient.
Observation: The array values are in [1, 1e5]. So we have a fixed universe of possible values (say up to V=1e5). The frequencies in a subarray are essentially the count of occurrences of each value in that range.
Thus a type 1 query is: given range [l,r], compute the multiset of non-zero frequencies (cnt_v for v in U where cnt_v>0). Then sort them, and compute min diff between k-th consecutive. So we need to get the distribution of frequencies in a range quickly, and then find the k-th order statistics of the frequencies (or rather the sorted list). That's heavy.
Given that we also have point updates, it's like we need a data structure that supports point updates and range queries to retrieve a histogram of frequencies, and then answer a min-diff query on the sorted frequencies. n,m up to 1e5, V=1e5. A typical approach could be Mo's algorithm with updates? Because there are updates. But m up to 1e5, Mo's with updates (Modifiable Mo's) might be feasible: O((n+m)*n^{2/3})? Possibly. But we also need to answer the min-diff over sorted frequencies quickly for each query. That is not trivial: we need to maintain a data structure that supports insert/delete of a frequency count (when a value's count changes) and query: given k, find min range of k frequencies. We need to support dynamic multiset of frequencies (counts per distinct value) and answer min difference over k consecutive elements in sorted order. That's a non-trivial data structure.
Alternatively, maybe we can solve the problem with segment tree of bitsets? But frequencies can be up to n, so not.
Another angle: Since values are only up to 1e5, we can consider using a BIT or segment tree to maintain for each value its positions? Then for a range query, we can compute frequency of each value that occurs via some method? That would be O(number of distinct values in range) which could be O(n) per query worst-case.
But note that k can be up to 1e5, but the number of distinct values in a range is at most r-l+1 <= n, but could be large.
We need to answer many queries (at most m). Could there be a simpler interpretation?
Maybe the answer can be derived without sorting all frequencies? Possibly using binary search on dif? For a given dif, can we check if there exist k distinct values with counts whose max-min ≤ dif? That is: can we find k frequencies within an interval of length dif? Equivalent to: Is there an interval [L, L+dif] such that at least k distinct values have frequencies in that interval? Since we can pick any k distinct values, we just need at least k values with frequencies lying within some window of size dif. Then answer is the smallest dif for which this holds. That's a classic binary search approach: we want minimal dif such that there exists a window of length dif that contains at least k frequencies.
So we can binary search dif per query? That would be O(log n) checks per query. Each check: given range [l,r] and a dif, we need to determine if there exists a value L (integer) such that the number of distinct values v with cnt_v in [L, L+dif] is at least k. And cnt_v is the frequency of v in [l,r].
We need to support many such checks across queries, and updates. Could we use a data structure that can, for a given range [l,r], get the multiset of frequencies? That seems heavy.
Alternative: Use sqrt decomposition on array? For each block, precompute something? Updates are point updates.
Given constraints, maybe a data structure like wavelet tree or segment tree with bitset could work? But we need frequencies, not just presence.
Another thought: Since values are up to 1e5, we could maintain for each value a BIT of positions. Then for a query range, we can compute frequency of a specific value quickly O(log n). But to test existence of a window of size dif, we would need to consider many values, which is not efficient.
Maybe we can use offline processing with CDQ? But queries are online? Actually we just need to output answers in order, but offline is allowed if we can process in order? Possibly we can rearrange? But there are updates interleaved with queries, so offline might be possible using time-based segment tree (like divide and conquer on time) but still need to answer queries about range frequencies and check condition.
Maybe we can use a segment tree where each node stores a sorted vector of frequencies? Not exactly because frequencies depend on range.
Consider using segment tree with "merge sort tree" that stores sorted list of values. That can answer number of occurrences of a specific value? Not directly; we can count occurrences of a value in a range in O(log^2 n) by binary search on the sorted lists. So we can get cnt_v for any v in O(log^2 n). To check the window condition, we need to know how many v have cnt_v in some interval. That's like we have a function f(v) = cnt_v (for v in [1,V]), and we want to count number of v such that f(v) ∈ [L, L+dif]. But f(v) is computed via range counting over positions of value v. This is like we have V=1e5 separate BITs, each BIT for positions of that value. Counting cnt_v for each v individually would be O(V log n) per check, too heavy.
Maybe we can use Mo's algorithm with updates, because the number of queries of type 1 is at least 1 but could be many (up to m). Modifiable Mo's (Mo's with updates) can handle up to 1e5 with O((n+m)*n^{2/3}) operations, which might be about 1e5 * 1e5^{2/3} ~ 1e5 * (1e5^{0.666}) ~ 1e5 * 2e3 = 2e8 maybe borderline but possible in C++ with optimization. However, we also need to maintain a data structure that can answer the minimal dif for given k quickly as we add/remove elements to the current range and apply updates.
In Mo's with updates, we treat updates as modifications that can be applied during movement in time. The current state is defined by the array after certain number of updates, and the current range [l,r]. For each query (type 1), we need to output answer based on the frequencies of values in the current range.
We need a data structure that supports:
- Insert a value x into the multiset (i.e., increase frequency of x by 1)
- Delete a value x (decrease frequency by 1)
- Query: given k, compute minimal possible max-min among k distinct frequencies, i.e., if we have multiset of frequencies (with counts per distinct value), we need to find the smallest dif such that there exists a window of size dif containing at least k frequencies. That's equivalent to: the minimal difference between the k-th smallest in sorted order is the minimal (F[i+k-1] - F[i]) over sorted frequencies.
So we need to maintain a dynamic multiset of frequencies (non-zero) that supports insert/delete of a frequency value (frequency changes by ±1 for a particular value). And we need to quickly answer that query.
We can think of maintaining the frequencies of each value in a hash map: freq[x] is count of value x in current range. When we add an occurrence of x, freq[x] increases by 1; when we remove, it decreases by 1. We need to maintain a data structure over the collection of frequencies (the values of freq[x] for x with freq>0). This data structure should support:
- Increase count of a key: it may change its frequency from old to new. So we need to remove old frequency from the multiset and insert new frequency.
- Query: given k, compute min over i of (sorted[i+k-1] - sorted[i]), where sorted is the current multiset of frequencies.
Let D be number of distinct values in current range (size of multiset). D can be up to O(n) in worst case (if all distinct). So we need to handle up to 1e5 elements.
We need to support operations in maybe O(log n) each (since total operations in Mo's can be ~1e5 * sqrt(n) or n^{2/3}, so O(log n) per operation may be acceptable if total operations ~1e7). But we also need query to be fast, maybe O(log n) or O(log^2 n) as well.
So we need a data structure for dynamic order statistics that can compute the minimal difference between elements that are k apart. Let's denote the multiset S of frequencies (positive integers). We need to compute min_{i} (s_{i+k-1} - s_i) where s_i are sorted S.
This is similar to "sliding window minimum difference" on a dynamic set.
If we maintain a balanced BST (like std::multiset) that stores all frequencies sorted, we can get the sorted list by traversing, but we need to compute this min difference efficiently. We can augment the BST to store additional information to answer this query. For example, we could maintain a segment tree over the frequency values (which are counts up to n) that tracks how many distinct values have each frequency. Since frequency values are in [0, n] (0 not included), we can maintain an array cntFreq[f] = number of distinct values with frequency f. Then S is essentially the multiset of frequencies with multiplicities equal to cntFreq[f] (since multiple values can have same frequency). The sorted list of frequencies is like the list obtained by listing each frequency as many times as cntFreq[f]. Then we need to compute the minimum difference between the (i+k-1)-th and i-th element in this multiset.
If we have the count per frequency, we can treat it as an array over frequency values from 1 to n (since frequencies >0). The total number of distinct values is sum cntFreq[f] = D, which can be up to n.
Now, to compute min_{i} (s_{i+k-1} - s_i), we need to find the smallest possible window span that covers k elements in this weighted sorted list.
Observation: This is equivalent to: find minimal d such that there exists a frequency value L where the total number of elements with frequencies in [L, L+d] is at least k. Because if you take the k elements that are in a window of size d, the difference between the max and min in that set is at most d. However, note that the window defined by the sorted list might have gaps: you can select elements that are not all consecutive in frequency value, but in the sorted list they will be interleaved with duplicates. However, if we want to minimize the difference between the largest and smallest, it's optimal to take a set of k elements that are all within a contiguous interval of frequency values (because if there is a gap, the range would be larger). More formally, for any set of k frequencies, if we let min = m, max = M, then all selected frequencies lie in [m,M]. The number of frequencies (with multiplicities) in [m,M] is at least k. So if we consider the interval [m,M], its length is d = M-m, and the total count in that interval is >=k. Conversely, if there is an interval of length d with count >= k, we can select k elements from it, and the range will be at most d (maybe less if we pick a subset that doesn't span the whole interval). But the minimal possible d for which we can select k elements is the minimal d such that there exists an interval of length d with total count >= k. However, is the answer exactly that minimal d? Not exactly: The answer is min_{i} (s_{i+k-1} - s_i). This is the minimal possible difference between the max and min among any k elements taken consecutively in sorted order. But note that if you take k elements not necessarily consecutive in sorted order, the range could be smaller? Let's check: Suppose frequencies: [1, 10, 10, 10] and k=3. The sorted list: 1,10,10,10. Consecutive windows of length 3: (1,10,10) diff=9, (10,10,10) diff=0. min diff = 0. For interval length approach: For d=0, intervals of length 0 (single frequency) with count >=3? At frequency 10, count=3 => total count in [10,10] =3 >=3, so d=0 works. So answer 0. That matches. Suppose frequencies: [1,2,100] k=2. Sorted: 1,2,100. Consecutive windows of length 2: (1,2) diff=1, (2,100) diff=98. min diff=1. Interval approach: For d=0: no frequency with count >=2, so no. For d=1: intervals of length 1 (i.e., [L, L+1]). Check [1,2]: count=2 (since frequencies 1 and 2 are in [1,2]) => >=2, so d=1 works. That matches answer 1. So indeed, the answer equals the smallest d such that there exists an interval [L, L+d] (with integer endpoints) where the total number of frequencies (counts of distinct values, with multiplicities) is at least k.
But careful: The interval length d includes both endpoints, so the difference max-min = d. The minimal d such that some interval of length d contains at least k frequencies is exactly the minimal possible max-min for k frequencies. Because if you have k frequencies within [L, L+d], you can take those k, and the max-min ≤ d. Conversely, if you have a set of k frequencies with max-min = d, then they all lie in [min, max] of length d, so that interval contains at least k frequencies. So the minimal d is the answer.
Thus the query reduces to: given multiset of frequencies (with counts per distinct value), find the smallest d >=0 such that there exists an integer L where sum_{freq in [L, L+d]} cntFreq[freq] >= k. Equivalent to the smallest window length that covers at least k points on the integer line where points are frequencies with weights = cntFreq[freq].
This is a classic problem that can be solved with two pointers if we have the list of frequencies sorted. But we need to answer after updates, dynamic.
We can maintain cntFreq array (size up to n) and also maybe a data structure that can answer: given d, can we check if there exists an interval of length d with sum of cntFreq >= k? But we need to find the minimal d. That could be binary searched on d from 0 to n (since max frequency <= n). For each d, we need to check if max window sum of cntFreq over intervals of length d is >= k. That is like: given array cntFreq[1..n] (sparse, many zeros, total sum D), we want to know the maximum sum over any interval of length d (or d+1? careful: interval [L, L+d] inclusive has length d? Actually the difference between max and min is d, so the number of integer points included is d+1 if we consider inclusive? Let's define d as max-min. If we take interval [L, L+d], then the values that are in that interval have max-min ≤ d. So interval length in terms of value difference is d. But the number of integer frequencies included is d+1 (if we consider all integer frequencies from L to L+d inclusive). However, the condition sum_{f in [L, L+d]} cntFreq[f] >= k. So the window length in terms of index span is d (difference). For a given d, we need to check if there exists L such that sum_{f=L}^{L+d} cntFreq[f] >= k. That's a sliding window maximum sum problem on array cntFreq. Since cntFreq is an array of length N = max possible frequency (<= n), we can precompute prefix sums, but dynamic updates change cntFreq values at two frequencies (when a value's frequency changes from f to f+1, cntFreq[f] decrements, cntFreq[f+1] increments). So we need a data structure that supports point updates (add/subtract 1 at indices) and queries: for a given d, get the maximum sum over windows of length d (or d+1? Actually length in terms of number of indices = d+1 because inclusive). Let's denote W = d+1. Then we need max sum over contiguous subarrays of size W (where W = d+1). So we need to answer: is max_{i} sum_{j=i}^{i+W-1} cntFreq[j] >= k?
Then we binary search d from 0 to n-1 (since max difference can be up to n-1). For each d, we need to answer that query. If we can answer it quickly, we can binary search per query. However, binary search per query would be O(log n) checks, and each check we need to compute max sliding window sum in cntFreq array dynamically. Can we support that efficiently with updates? Possibly using a segment tree that maintains for each node something like maximum subarray sum, but here we need maximum sum for a fixed window size W. That's different: we want maximum sum over intervals of exactly length W. That's like we have array A[1..N] (N = n), we need to support point updates and query: max_{i} (prefix[i+W-1] - prefix[i-1]) for given W. That can be done by maintaining a Fenwick tree for prefix sums and then we need to find maximum difference between two prefix sums that are W apart. Specifically, for each i, sum_{j=i}^{i+W-1} A[j] = P[i+W-1] - P[i-1]. So we need max_{i} (P[i+W-1] - P[i-1]). For a given W, this is like we have two arrays: prefix sums. We can maintain a segment tree that stores prefix sums? But point updates cause many prefix sums to change. Another approach: Use a segment tree where each node stores the maximum of (P[i+W-1] - P[i-1]) for i in its range? But W changes per query, so it's not static.
Thus binary search on d with per-check O(log n) might be possible if we can compute max sliding window sum for any W quickly after updates. Could use a Fenwick tree and then for each check we need to compute the maximum of P[i+W-1] - P[i-1] over i. That can be done by scanning with a deque if we had static array, but dynamic and many checks is heavy.
Alternatively, we could compute the answer directly without binary search by using a two-pointer on the sorted list of frequencies. But we need to maintain that list dynamically. Maybe we can maintain an order statistic tree of frequencies, and also be able to compute the minimal difference between k-th consecutive elements. That might be done by maintaining a balanced BST (like a treap) that stores frequencies, and we need to support: insert a frequency, delete a frequency, and query: min_{i} (s_{i+k-1} - s_i). This is similar to maintaining the multiset and being able to quickly compute the minimum gap between elements that are k apart.
We can augment each node in a balanced BST with additional info: the sorted values, and maybe we can compute the answer by looking at differences between certain neighbors? Since k can vary per query, we might need to compute for the current set and given k. That seems like a range query over the sorted list.
One approach: Since the frequencies are integer values up to n, we can use a segment tree over the frequency domain (1..n) where each leaf stores cntFreq[f]. Then we can answer the minimal d by binary searching on d using segment tree to get maximum sliding window sum? Actually, we can binary search d and for each d, check max sum over window size W = d+1 using segment tree that can answer maximum subarray sum of fixed length? That's not typical. But maybe we can answer the existence of interval with sum>=k directly without binary search, by using two pointers on the frequency axis while maintaining the current sum. However, we need to answer multiple queries on the same snapshot (current frequencies). But we could for each query of type 1, we have a current state of frequencies (after some updates). We could iterate over frequencies in order and apply two pointers to find minimal window length that achieves sum>=k. That would be O(number of distinct frequencies) which could be up to n (1e5) per query, and with many queries, too slow.
But maybe the number of type 1 queries is not too high? It says at least one, but could be up to 1e5. So we need something efficient.
Let's think about the problem's constraints: n,m up to 1e5, values up to 1e5. Mo's algorithm with updates may be acceptable. In such algorithm, we have about O((n+t) * n^{2/3}) operations where t is number of queries? Actually, for Mo's with updates, if we have n elements, u updates (type 2), q queries (type 1), we can process in O((n+q) * n^{2/3}) or similar. Usually total complexity O((n+q) * n^{2/3}) with a factor of about O(1) for add/remove if we maintain a data structure with O(1) updates and O(√n) query? Wait, typical Mo with updates complexity: O((n+q) * n^{2/3}) if we handle add/remove in O(1). But here our add/remove will involve updates to the frequency multiset, which we hope to do in O(log n). That might push to O((n+q) * n^{2/3} * log n), which could be borderline but maybe okay if constants low (n=1e5, n^{2/3} ~ 2150, times (n+q) ~ 2e5 => 4.3e8 * log n ~ 4e9 too high). So need O(1) or very cheap operations.
Alternatively, maybe there is a simpler solution using segment tree of vectors plus binary search? Let's consider whether the answer can be expressed in terms of order statistics of frequencies. Could it be that the answer is simply 0 if there is any frequency that occurs at least k times? Actually, if there is a frequency value that appears as count for at least k distinct numbers, then we can choose k numbers all having that same frequency, dif=0. But if not, we need to consider different frequencies. But not simpler.
Another angle: Since values are only up to 1e5, we might be able to use a "value frequency" segment tree: each value is a point, and we maintain a segment tree over the values where each leaf stores the frequency of that value in the current range? But the range query is on the array positions, not on values. We need to compute frequencies of each value in a subarray quickly. That's like a 2D problem: we have positions and values. Could we use a BIT of BITs? For each value, maintain BIT of positions; then to get all frequencies we would need to iterate over values, which is too many.
Maybe we can use sqrt decomposition on values: Group values into buckets of size B. For each bucket, we can maintain a data structure that can answer quickly for a range query: the frequencies of values in that bucket aggregated? For example, for each block of values, we could maintain a Fenwick tree over positions? Not exactly.
We could use offline processing with divide-and-conquer on queries (CDQ) and treat each query as asking for the minimal d. However, we need to output answer per query, and updates are interleaved. Possibly we can convert the problem into something like: For each possible frequency f, we need to know which values have that frequency. But again dynamic.
Given the difficulty, maybe there is an intended solution that uses a segment tree with "merge sort tree" plus binary search? Wait, maybe we can answer query of type 1 without constructing the whole list of frequencies, by using binary search on answer d and checking if there are k distinct values with frequencies in some window. The check could be done using a data structure that can count number of distinct values in a range that have frequency within [L, L+d]. But frequency is count of occurrences in subarray; it's a function of the range. So for a fixed query [l,r] and fixed d, we need to check existence of L such that the number of distinct values v with cnt_v in [L, L+d] is >= k.
But note that cnt_v is the number of times v appears in [l,r]. So we need to count distinct values v whose frequency in [l,r] lies in a given interval. That's a difficult range distinct count with condition on frequency.
There is known technique: For each value v, we can consider the positions of v. The frequency in [l,r] is the number of positions of v in [l,r]. So we need to count v such that the count of its positions in [l,r] is between L and L+d. This is like a "range range counting" problem: we have for each value v, a set of positions. For query [l,r], we need to count v such that the number of positions in [l,r] is in a given range.
We could possibly use wavelet trees or segment tree on positions storing values, but then counting distinct values with frequency constraint is tough.
Maybe we can use "offline with sqrt" again.
Let's step back: The problem seems heavily data structure oriented. Could it be that the solution uses a segment tree where each node stores the multiset of frequencies of its segment? But merging two children's frequency multisets is not trivial; it would be like merging two histograms. However, we might store the frequencies of values for that segment: e.g., for each value, the count in that segment. That would be too large.
But note values are up to 1e5, n up to 1e5. If we build a segment tree, each leaf corresponds to a single element. Each internal node stores a map from value to its frequency in that segment. The total size would be O(n log n) if we use sparse representation? Actually, if we store for each node the frequencies of all values appearing in that segment, total storage would be O(n log n) because each occurrence contributes to O(log n) nodes. Since each position has one value, the total number of (value, node) entries is n * O(log n) = O(n log n). That's about 1e5 * 17 ~ 1.7e6, which is manageable. Then we could answer a query by merging O(log n) nodes' frequency maps to get the overall frequency map for the range. Merging these maps could be done by taking the union and summing counts. But if we do this per query, we would need to combine up to O(log n) maps, each of which could be large (size up to segment length). In worst case, the total distinct values in a range could be O(n), so merging O(log n) maps could be O(n) per query, too slow.
But maybe we can use a segment tree that stores the frequency vectors in a compressed way (like using bitsets) and use fast operations? Not likely.
What about using sqrt decomposition on array: Divide array into blocks of size B ≈ sqrt(n) ~ 316. For each block, we can precompute the frequency of each value within that block. Then for a range query, we can combine O(sqrt(n)) blocks (full blocks) and partial edges. For each full block, we have its frequency histogram. We can add these histograms to accumulate total frequencies for the range. This is similar to offline approach: for each query, we could build the frequency map by adding contributions from O(sqrt(n)) blocks. That would be O(sqrt(n) * V) if we add whole histograms naively, but we can add only the values that appear? However, each block histogram may contain many zeros if we store only non-zero entries. Since total distinct values per block is at most B, each block's histogram has at most B distinct entries. Summed over all blocks, total non-zero entries across all blocks is n (each position contributes to its block). So each block's histogram size is O(B) on average, but worst-case block could have B distinct values, which is up to sqrt(n). So combining O(sqrt(n)) blocks would give total O(n) per query if we merge many distinct values. Not good.
But maybe we can answer type 1 queries using a different insight: The answer is the minimal d such that there exists a frequency range containing at least k frequencies. This is like a range query on the frequency domain after we compute the frequencies. Could we precompute for each possible d something? Unclear.
Given that n,m ≤ 1e5, maybe a solution with O((n+m) sqrt(n)) is acceptable if constants are small and operations per add/remove are O(1). Mo's algorithm is typical for problems with range queries and updates, with O((n+q) n^{2/3}) and add/remove O(1). However, here we also need to answer a more complex query on the frequencies, which would require maintaining a data structure that can answer the min d for any k quickly. But perhaps in Mo's, we can compute the answer for each query from scratch after finishing the add/remove movements? That would be O(D) per query, where D is number of distinct values in the current range, which could be O(n). That's too slow if many queries.
But if we maintain the cntFreq array (frequency of frequencies) and also maintain a data structure to compute minimal d for given k, we can answer query in O(log n) or even O(1). So we need that DS to support:
- increment/decrement cntFreq at a specific index (when a value's frequency changes)
- query: given k, find smallest d such that max window sum of length d+1 (over cntFreq) >= k.
Let's think about this DS.
We have an array A[0..n] (we can ignore 0), where A[f] = number of distinct values with frequency f in current range. The total sum of A[f] = D (number of distinct values). We need to support point updates: A[f] += delta (delta is +1 or -1). After each update, we may need to answer queries. But note that we have many updates (add/remove operations) during Mo's, and then we answer some queries.
We need to support the query: find minimal d such that max_{i} sum_{j=i}^{i+d} A[j] >= k. Since A is non-negative integer array.
We could precompute prefix sums P[i] = sum_{j=1}^{i} A[j]. Then the sum over [i, i+d] = P[i+d] - P[i-1]. For a fixed d, we need to check if max_{i} (P[i+d] - P[i-1]) >= k. This is equivalent to: max_{i} (P[i+d] - P[i-1]) = max_{j} (P[j] - min_{t <= j-d} P[t])? Actually, if we fix d, then for each i, sum = P[i+d] - P[i-1]. So we need to compute the maximum difference between two prefix sums that are exactly (d+1) apart (index difference d+1). This can be done with a segment tree that stores prefix sums, but updates to A cause updates to many prefix sums (from that index onward). However, we can maintain a Fenwick tree for A, and then for a fixed d, we could compute all these sums by iterating i? Not feasible.
But maybe we can answer the query directly without binary search on d by using two pointers on the frequency axis while maintaining the window sum, but we need to do that for each query after many updates. However, if we maintain the cntFreq array, we can run a two-pointer scan to find the minimal d. Since the frequency domain size is up to n (1e5), scanning each time O(n) might be okay if the number of type 1 queries is not huge. But worst-case could be 1e5 queries, leading to 1e10 operations.
But perhaps we can optimize by noting that the total number of distinct frequencies D is the number of distinct values in the current range, which could be up to n, but the sum of D across all queries might be large if we do Mo's? Not if we answer each query after building the frequency map; but if we answer by scanning the cntFreq array each query, that is O(n) per query, too much.
We need a DS that can maintain the answer for all possible k? Actually k varies per query, so we need to answer for given k.
Maybe we can maintain a segment tree over frequency axis that can answer for any k the minimal d quickly? Let's think about the problem: For array A (non-negative), we want the smallest d such that there is a subarray of length d+1 (contiguous) with sum >= k. This is similar to the classic problem of "minimum length subarray with sum >= k" but here we have A as the array, and we want the minimum length (which is d+1) such that some subarray of that length has sum >= k. However, note that we want the minimum d, not the minimum length; length = d+1. So we want minimal L (length) such that max sum over subarrays of length L >= k. Then answer = L-1. So we need to find the smallest L (>=1) where the maximum sum over subarrays of length L is at least k. Since A is non-negative, the maximum sum over subarrays of length L is a non-decreasing function of L (because if you increase L, you can always take a longer subarray that includes the max sum of shorter length? Actually, with non-negative A, the maximum sum over subarrays of length L is non-decreasing with L? Let's check: If A has non-negative values, then the maximum sum for length L+1 is at least as large as for length L, because you can take the best length L subarray and extend by a non-negative element. But careful: the best length L subarray might be at the boundaries; to get length L+1, you might need to include an element outside, which could be zero, so sum doesn't decrease. So max sum over subarrays of length L is monotonic non-decreasing with L. So we can binary search L (or d) on the answer.
Thus for each query, we can binary search L (length = d+1) from 1 to n, and check condition: max sum over subarrays of length L >= k. Since max sum is monotonic in L, binary search works.
Now, we need a data structure that can answer, for any given length L, the maximum sum of A over a contiguous subarray of exactly length L. And we need to support point updates to A (which are increments/decrements by 1 at positions). Also, A's indices are from 1 to n (since frequencies cannot exceed n). So we need to support:
- point update: A[pos] += delta.
- query: given L, return max_{i} sum_{j=i}^{i+L-1} A[j].
This is a classic problem: Range maximum sum of fixed length L with point updates. This can be solved using a segment tree where each node stores the sum of that segment, and we need to answer maximum sum over intervals of length L. This is like a sliding window maximum of the prefix sums: sum_{i}^{i+L-1} A[i] = P[i+L-1] - P[i-1]. So we need to maintain the prefix sums P[0..n] (with P[0]=0). Then the max over i of P[i+L-1] - P[i-1] for i from 1 to n-L+1. If we maintain the array P in a data structure that supports point updates to A (which cause range updates to P: adding delta to P[j] for all j >= pos). That is, if A[pos] changes by delta, then all P[j] for j >= pos change by delta. Then the query for a given L is: max_{i} (P[i+L-1] - P[i-1]) = max_{i} (P[i+L-1] - P[i-1]). This is equivalent to: for each i, it's difference between two prefix sums with fixed offset L. So if we maintain two copies of the prefix sum array shifted by L, we could compute the maximum. But L varies per query, so we need to answer for arbitrary L.
We could maintain a segment tree over the array of prefix sums? Let's consider: Let P[0..n] be the prefix sums. After an update to A[pos] by delta, all P[j] for j>=pos get increased by delta. That's a range add on P. And we need to answer queries: for a given L, compute max_{i=1..n-L+1} (P[i+L-1] - P[i-1]). This is like we have two sequences: X_i = P[i-1] and Y_i = P[i+L-1]. The expression is Y_i - X_i. So for fixed L, it's max over i of (Y_i - X_i). But Y_i is just X_{i+L}? Actually, P[i+L-1] and P[i-1] have indices offset by L. So if we define arrays, we could precompute for each possible L? That would be too many.
Alternatively, we could use a Fenwick tree to quickly compute any subarray sum, but we need the maximum over all subarrays of length L. That is like we need to compute the maximum of (prefix[i+L] - prefix[i]) for all i. This is essentially the maximum difference between two prefix sums at distance L. This can be computed if we maintain a data structure that can answer: given L, what is max_{i} (P[i+L] - P[i])? Since P is subject to range additions (when A changes). This is reminiscent of maintaining the convex hull of prefix sums? Not exactly.
Could we use sqrt decomposition on the frequency axis? Since n=1e5, we could maintain A in an array and for each query we could compute the max sliding window sum in O(n) by scanning with a deque? That's too heavy.
But maybe we can answer the binary search per query using a segment tree that can answer max subarray sum for any length? Actually, we can answer the condition "max sum over subarrays of length L >= k" using a segment tree that stores for each node the sum of that segment, and also the maximum sum of any subarray of exactly length L? But L varies, so we would need to query for each L separately. That would be difficult.
Alternative: Instead of binary searching L, we could compute the minimal L directly by maintaining something like the "smallest L such that max window sum >= k" can be found by scanning L from 1 upward until condition holds, but that's O(n) per query.
Given the constraints, maybe the intended solution is indeed Mo's algorithm with a data structure that maintains cntFreq and also maintains the answer for all possible k? Or we can maintain a data structure that directly stores the sorted list of frequencies and can answer the min difference for a given k quickly. Let's explore this.
We maintain a multiset S of frequencies (positive integers). We need to answer: min_{i} (s_{i+k-1} - s_i). Let's denote the sorted array as s[1..D]. This can be computed by scanning i and taking min difference between s[i+k-1] and s[i]. So if we could maintain the sorted list in a balanced BST where each node stores the value, we could also precompute the differences between elements that are k apart. Since k changes per query, we need to answer for arbitrary k. That seems like we need to support order statistics and compute differences between the i-th and (i+k-1)-th smallest. The minimal difference is essentially the minimal gap between two elements that are k-1 apart in sorted order.
We could maintain a data structure that, for each possible gap (difference between two elements) maybe we can keep something? But k varies.
Alternatively, we can note that the answer is simply the minimal L-1 where L is the smallest window length (in terms of frequency value) that contains at least k frequencies. And this L is the smallest integer such that max sum over subarrays of length L in cntFreq >= k. Since cntFreq is non-negative, the function f(L) = max sum over subarrays of length L is non-decreasing. So we could precompute f(L) for all L? But that would be O(n^2) to compute initially and updates would be heavy.
Maybe we can maintain cntFreq and also maintain a segment tree that for each node stores the maximum sum for every possible length? That would be too heavy.
But perhaps we can answer the query by using a "two pointers" method on the fly using the cntFreq array, but we can do it in O(answer) time? Not sure.
Let's reconsider Mo's algorithm. In Mo's with updates, we have operations: add an element (increase frequency of its value), remove an element (decrease frequency). We need to support query for k. Maybe we can maintain a Fenwick tree over frequency domain that can answer, for a given d, the maximum window sum? Or maybe we can maintain a data structure that directly gives the answer for the current multiset. Since k is given per query, we could compute the answer by scanning the cntFreq array only when a query arrives, but we hope that the total time across queries is manageable if we do it efficiently. Could we use a "sweep" approach: maintain cntFreq, and also maintain an auxiliary structure that can answer minimal d quickly using something like "convex hull"? Possibly we can use a segment tree that stores, for each segment, the maximum prefix sum, maximum suffix sum, total sum, and also maybe something about windows? But the window length is not fixed.
Wait, we need the maximum sum over any subarray of a given length L. This is known as the "maximum sum subarray of fixed length". It can be answered in O(1) after O(n) preprocessing if array static, but with updates we need dynamic.
Given that A is an array of size up to n (1e5) and we have up to O((n+q) * n^{2/3}) updates (like 2e7) in Mo's, we cannot afford O(log n) per update if we also need to answer queries quickly. But maybe the number of updates in Mo's is less? Let's compute typical Mo's with updates: We have three dimensions: l, r, time. We sort queries and process in blocks. Complexity O((n+q) * n^{2/3}) if block size = n^{2/3}. For n=1e5, n^{2/3} ≈ (1e5)^{0.6667} ≈ 10^{5 * 0.6667} = 10^{3.3335} ≈ 2154. So total moves ≈ O((n+q)*n^{2/3}) = up to (2e5)*2154 ≈ 4.3e8 moves. That's high but maybe borderline in C++ with simple operations. However, if each move (add/remove) involves O(log n) operations, it could be too slow.
But maybe we can choose block size to optimize: Usually Mo's with updates complexity O((n+q) * n^{2/3}) is derived with block size = n^{2/3} and O(1) add/remove. If add/remove is O(1), 4.3e8 may be okay in 2 seconds? Usually 1e8 is borderline; 4e8 likely too high. So we need a more efficient approach.
Alternative: Use sqrt decomposition on array to answer queries directly without Mo's? Let's think about the problem again: We have array with point updates and range queries that ask about frequencies. Could we use a data structure like "Binary Indexed Tree of Fenwick trees" for each value? Not.
Maybe we can use "Wavelet Matrix" or "Wavelet Tree with updates"? Not straightforward.
Maybe we can use "segment tree with bitset" but frequencies can be up to n, so we can't use bitset of size n per node.
Another idea: The answer is the minimal d such that there exists a frequency range with total distinct values >= k. This is like we are looking at the histogram of frequencies. Since frequencies are bounded by n (≤1e5), we could maintain for each possible frequency f the count of values with that frequency. Then we need to answer the minimal window length L such that max sum over subarray of length L >= k. This can be done by maintaining a segment tree where each leaf corresponds to frequency f, storing A[f]. Then for each node, we could store the maximum subarray sum for each possible length? No.
But maybe we can answer the query by binary search on L and using a segment tree that can compute maximum subarray sum of any length? Not directly.
However, we can compute the maximum subarray sum of a fixed length L using a segment tree that stores prefix sums? Wait, if we have the array A, we can compute for each i the sum of length L starting at i: S_i = sum_{j=i}^{i+L-1} A[j]. We want max S_i. This is like we need a data structure that can answer range maximum of S_i values, but S_i depends on L. But note that S_i = prefix[i+L-1] - prefix[i-1]. So if we maintain the prefix sum array P, then for a given L, the values we care about are P[i+L-1] - P[i-1] for i=1..n-L+1. So it's the difference between two prefix sums. If we could maintain two copies of the P array offset by L, we could take max of their difference. But L changes per query, so we would need to rebuild that structure per query.
Maybe we can avoid binary search by using a two-pointer approach on the frequency axis that runs in O(D) per query, but D may be large. However, we could limit D to the number of distinct values in the range, which might be less than sqrt(n) on average? Not guaranteed.
Maybe we can use an offline approach where we process all queries of type 1 together, using divide-and-conquer on answer? For each query, we can binary search the answer, and then we need to check condition. The check is: for a given d, is there an interval of length d+1 with sum >= k? This check can be done using a data structure that supports range frequency counting for each value? Not exactly.
Let's attempt to design a data structure for the check: given [l,r], d, k, we need to know if there exists L such that number of distinct values v with cnt_v in [L, L+d] >= k. This is like we have for each value v, its frequency f_v = count of v in [l,r]. We need to know if there are at least k v with f_v in some interval of length d. This is a 2D condition: we have values v (from 1 to V) and frequencies f_v. We want to know if there exists a horizontal band (range of frequencies) of height d+1 that contains at least k points (v, f_v). Since v is just an index, it's essentially a set of points (v, f_v) where f_v > 0. The condition is: is there a horizontal strip of height d+1 that covers at least k points? This is like we need to determine the maximum number of points in any strip of that height. For a given set of points (v, f_v) (v arbitrary), the maximum number in a horizontal strip of fixed height can be found by sorting points by f_v and using two-pointer. But we need to answer this for many queries and with updates.
Maybe we can use a segment tree over the array positions to compute the frequencies? Actually, for each query [l,r], we have a set of frequencies for each value. We could try to compute them using a segment tree that stores for each node a histogram of frequencies? But that's large.
Alternative approach: Because the values are bounded by 1e5, we might use sqrt decomposition on values. For each block of values, we can maintain a data structure that can answer for a given range [l,r] the frequencies of values in that block? For a query [l,r], we can iterate over blocks and for each block, we can compute the frequencies of each value in that block by scanning the positions? Not efficient.
Maybe we can precompute for each value its positions, and then for a query we can binary search to get frequency. To check the condition for a given d, we need to find if there exists L such that at least k values have frequency in [L, L+d]. This is like we have an array of frequencies (indexed by value). We need to find the maximum number of values in any sliding window of length d on the frequency axis. But we also need to know the frequencies themselves for all values present in the range. We could compute all frequencies by iterating over values that appear in the range? That could be many.
But perhaps we can use the fact that the sum of frequencies over all values equals length of range, which is at most n. So the number of distinct values D plus the sum of frequencies is the range length. Not helpful.
Given the difficulty, I'm leaning towards Mo's algorithm with a clever DS that can answer query in O(log n) or O(√n). Let's explore the DS for maintaining the array cntFreq (frequency of frequencies) and answering min L (or d) such that max subarray sum of length L >= k.
We need to support point updates (A[f] += delta) and query: smallest L with max window sum >= k.
Since A is non-negative and we only need to answer this query occasionally (for each type 1 query), maybe we can compute the answer by scanning only the non-zero entries of A. The number of non-zero entries is at most number of distinct frequencies that actually appear, which is at most number of distinct values D. And D is at most sqrt(2*range length)? Not necessarily; D can be up to n. But maybe in practice it's less? But we need worst-case guarantee.
But note that the total sum of A[f] over all f is D (the number of distinct values). D can be up to n. However, the number of distinct f values (i.e., frequencies that actually occur) is at most O(√(total sum of frequencies?))? Actually, if there are D distinct values, their frequencies sum to the range length len = r-l+1. The number of distinct frequency values possible is at most O(√len) because if frequencies are all distinct, they must be 1,2,3,... up to t such that sum = D(D+1)/2 ≤ len => D ≤ O(√(2len)). So interesting: In any subarray, the number of distinct frequencies (i.e., the number of different count values) is O(√len). Why? Because if we have D distinct values, each with frequency f_i, and all f_i are distinct positive integers, then the minimum sum of D distinct positive integers is 1+2+...+D = D(D+1)/2. Since sum of frequencies = len, we have D(D+1)/2 ≤ len, so D ≤ O(√(2len)). So the number of distinct frequency values is at most about √(2len) ≤ √(2n) ≈ 447 for n=1e5. That's promising!
Let's verify: The distinctness of frequencies is not guaranteed; many values can share the same frequency. So the number of distinct frequency values (i.e., the set of f such that cntFreq[f] > 0) could be much smaller than D. In worst-case, all D values could have the same frequency, then the number of distinct frequency values is 1. The worst-case for number of distinct frequency values is when frequencies are all distinct, and that forces D ≤ O(√len). So indeed, the number of distinct frequencies (let's call it F) is O(√len) ≤ O(√n) ≈ 316 for n=1e5. Actually, √(1e5) ≈ 316, but we got 447 from D(D+1)/2 ≤ len => D ~ sqrt(2*1e5) ≈ 447. So it's about 447. So the number of distinct frequency values in any subarray is at most about 447. That's small! That is a key observation.
Let's double-check: Suppose len = 1e5, we could have D = 1e5 distinct values? If each value appears exactly once, then frequencies are all 1. So distinct frequency values = 1, not large. To have many distinct frequencies, we need many different frequencies. For frequencies to be distinct, the smallest possible sum for D distinct positive integers is D(D+1)/2. Since the total length is len, we have D(D+1)/2 ≤ len, so D ≤ about sqrt(2len). So indeed, the number of distinct frequencies (i.e., the cardinality of the set of frequencies) is at most O(√len). So F = O(√n). This is a crucial bound.
Thus, the array cntFreq has only O(√n) non-zero entries. Even though its length is up to n, only O(√n) indices have positive values. So we can maintain a list of those indices (the frequencies that actually occur). When we update frequencies (increase or decrease), we may add or remove indices.
Now, for answering the query: we need to find minimal d such that there exists an interval of length d (i.e., frequency range of size d) covering at least k frequencies (with multiplicities). Since the number of distinct frequency values is small (O(√n)), we could simply gather all (freq, cnt) pairs (where cnt = number of distinct values with that frequency). Then we have a list of (f, w) where w = cntFreq[f] > 0. The total number of such pairs is F = O(√n). Then we can sort these pairs by f (they are already sorted if we maintain in a balanced BST or just gather and sort each query). Since F is small (max ~447), we can afford to sort them per query (O(F log F) ~ small). Actually, we might need to sort them each time; but we can maintain them in a balanced BST to keep them sorted automatically, so we can iterate in order quickly.
Given this list, we can compute the minimal window length that covers at least k elements (with weights w). This is a weighted sliding window problem on a small list. Since F is O(√n) ≤ ~447, we can do a two-pointer scan in O(F) time per query. That's very efficient.
Therefore, the main challenge reduces to maintaining the multiset of frequencies (i.e., the frequencies of distinct values in the current range) and being able to quickly update it when we add or remove an element from the range (as in Mo's algorithm). And we need to maintain the cntFreq array (counts of frequencies) and also the list of distinct frequency values (the ones with cntFreq>0). Since the total number of distinct frequencies is small, we can maintain this list in a balanced BST (like std::set) for the frequencies that have non-zero cntFreq. Each update (when a value's frequency changes from f to f+1 or f-1) will affect cntFreq[f] and cntFreq[f+1] etc. We can update the set accordingly: if cntFreq[f] becomes 0, remove f from set; if becomes 1 from 0, add f. That's O(log n) per update (since the set stores frequency values up to n, but number of entries is O(√n) only? Wait, the set stores the frequencies that have cntFreq>0. The size of this set is F, which is O(√n). So operations on this set are O(log F) which is O(log √n) ~ O(log n) but actually log of 447 is small, but we can implement with a balanced BST like std::set which is O(log n) because it compares integers; but that's fine as log n ~ 17. So per add/remove operation we can update cntFreq and the set of active frequencies in O(log n). That's acceptable.
Now, we also need to have the frequencies of each value (freq[x]) in the current range. In Mo's algorithm, we maintain an array freqVal[1..V] storing the current frequency of each value in the range. When we add a position with value v, we increment freqVal[v]. This changes its frequency from f to f+1. So we need to update cntFreq: decrement cntFreq[f] (if f>0), increment cntFreq[f+1]. Also update the set of active frequencies accordingly. Similarly for removal.
Thus each add/remove operation is O(1) (updating arrays) plus O(log n) for set insertion/deletion (if frequency becomes zero or new). That's cheap.
Now, for each query of type 1, we have the set of active frequencies (distinct f where cntFreq[f] > 0). Since the size of this set is O(√n) (actually bounded by about 447), we can extract the list of (f, cntFreq[f]) pairs. We need to sort them by f; but the set is already sorted (since it's a balanced BST of integers). So we can iterate over the set in order and for each f, we have cnt = cntFreq[f]. Then we need to find the smallest d such that there exists an interval [L, L+d] covering total weight >= k.
We can do a two-pointer scan over the sorted frequencies. Let the sorted frequencies be f_1 < f_2 < ... < f_M (M = number of distinct frequency values). For each f_i, we have weight w_i = cntFreq[f_i]. We want to find the minimal d = (f_j - f_i) such that the sum of weights from i to j is >= k. Since we want to minimize d, we can slide j while sum < k, then move i. Complexity O(M). Since M = O(√n) ≈ up to 447, this is trivial.
But careful: The interval length is d = f_j - f_i (since we consider inclusive interval from f_i to f_j, the difference is f_j - f_i, and the window length in terms of frequency difference is d, and the total weights in that interval is sum_{t=i}^j w_t. That's exactly the condition we need: find minimal d such that there exists i,j with f_j - f_i <= d and sum_{t=i}^j w_t >= k. However, note that the interval includes all frequencies between f_i and f_j, but we only have frequencies at discrete points; if there are gaps, the interval [f_i, f_j] may contain frequencies that are not present (with zero weight). That's fine because the sum over that interval is sum of weights of frequencies present in that interval. The condition for existence of a window of length d that covers at least k frequencies is: there exist i <= j such that f_j - f_i <= d and sum_{t=i}^j w_t >= k. Because we can take L = f_i, then the interval [L, L+d] includes up to f_j (since f_j - f_i <= d), and the sum of weights of frequencies in that interval is at least the sum from i to j, which is >= k. Conversely, if there is some interval of length d that captures a set of frequencies with total weight >= k, then the frequencies present in that interval are a contiguous subsequence in the sorted list (maybe not exactly, because there could be gaps: if the interval includes frequencies that are not present, it doesn't matter; the frequencies present are a subset, but they might not be contiguous in the sorted list if there are gaps? Actually, if we take an interval [L, L+d], the frequencies present are those f_t that satisfy L <= f_t <= L+d. Since f_t are sorted, they will form a contiguous block in the sorted list? Not necessarily if there are frequencies outside the interval interspersed? If we have frequencies f1 < f2 < f3, and interval [L, L+d] might include f1 and f3 but not f2 if f2 is outside the interval. However, since f1 and f3 are both in the interval, and f2 is between them but outside, that would mean f2 > L+d or f2 < L. But if f1 and f3 are both within [L, L+d], then because f1 < f2 < f3, f2 must also be between f1 and f3, so it must also be within [L, L+d] (since L <= f1 and f3 <= L+d, then any f between f1 and f3 is also between L and L+d). Therefore, the set of frequencies in an interval is contiguous in the sorted list. So indeed, if an interval covers some frequencies, the frequencies that lie in it form a contiguous segment in the sorted list. So the condition reduces to existence of a contiguous segment in the sorted list of (f, w) such that f_last - f_first <= d and total weight >= k. So our two-pointer over the sorted distinct frequencies works.
Thus we can compute answer as follows: If total distinct values D = sum w_i < k, answer -1. Otherwise, we use two pointers to find minimal d. Let i = 0, j = -1, sum = 0, ans = INF. While i < M: while j+1 < M and sum < k: j++, sum += w_j. Then if sum >= k, ans = min(ans, f_j - f_i). Then sum -= w_i, i++. Continue. This gives minimal difference between frequencies. That's O(M).
But we need to be careful: The answer is the minimal d such that there is an interval of length d (difference) that covers at least k frequencies (with multiplicities). However, our two-pointer as described ensures that the interval is from f_i to f_j inclusive, and we compute d = f_j - f_i. This yields the minimal d because any optimal interval will have its start and end at actual frequencies present (we can slide the interval to start and end at frequencies to minimize d). So that's correct.
Edge case: if k=1, answer should be 0 because we can choose any single value, dif = 0. Our two-pointer would yield minimal d = 0 because when i=j, f_j - f_i = 0, and sum >=1, so ans will be 0.
Now, we also need to confirm that the answer we compute is the minimal dif as defined: min over chosen k values of (max cnt - min cnt). In terms of frequencies, the minimal dif is exactly the minimal d computed as above. Because if we have a set of k values, their frequencies lie within some interval [min, max] of length d. The total weight in that interval is at least k. Conversely, if there is an interval of length d containing total weight at least k, we can select k values from it (any k) and the dif will be at most d (since max-min ≤ d). Moreover, if we take the interval that gives minimal d, the dif can be that d, and there might be a set with smaller dif if the interval contains more than k values and we can choose a subset with smaller spread? But if the interval has length d, any k values within it will have spread at most d. But could we pick k values that are not all within an interval of length less than d? The minimal dif is the minimum over all subsets of size k of (max-min). This is equivalent to the minimal d such that there exists an interval of length d containing at least k frequencies. Because if you have a set of k values with spread d0, they all lie in an interval of length d0, so d0 qualifies. Conversely, if there is an interval of length d containing at least k frequencies, you can pick any k from it, giving spread ≤ d. So minimal d (call it d_min) is the answer. And our sliding window on sorted frequencies gives that d_min.
Thus the solution reduces to being able to quickly compute the frequencies of distinct values in a subarray, and maintain the data structure to answer query type 1 with O(√n) processing per query after we have the frequency distribution.
Now, the main challenge: we need to compute the frequency distribution for each query. Since we have updates, we need a data structure to get the current array state and answer queries. Mo's algorithm with updates is a natural fit because it allows us to maintain a current range and current array state (with updates applied) and we can answer queries by adjusting the range boundaries and applying updates in order. In Mo's with updates, we treat each query of type 1 as a query with left, right, and a timestamp (number of updates before it). We'll sort queries and process them in blocks of time. The standard approach: block size = n^{2/3}. We'll maintain the current array state, the current frequencies in the current range, and also the cntFreq and set of active frequencies. Each add/remove operation updates freqVal[v] and updates cntFreq and active frequencies set. Since each operation is O(log n) (due to set operations), and total number of add/remove operations in Mo's is O((n+q) * n^{2/3}) as earlier, we need to compute if that's acceptable. For n=1e5, n^{2/3}=~2150, (n+q) could be up to 2e5, product = 4.3e8. Each operation does a few array updates and set insert/delete (O(log n) ~ 17). So total operations ~ 4.3e8 * small constant? 4.3e8 might be borderline but possibly pass in optimized C++ with fast I/O if we are careful. However, typical Mo's with updates has complexity O((n+q) * n^{2/3}) but that counts the moves of left/right and time. Each move does an add or remove of one element. So we would have about 4.3e8 add/remove operations. That's quite high; even with O(1) per operation it might be too slow. But perhaps we can reduce the constant by using a smaller block size? Actually, the complexity for Mo's with updates is O((n+q) * n^{2/3}) if we set block size for l as n^{2/3}, for time as n^{1/3}? Let's recall: In Mo's algorithm with updates (also called "query with updates"), we sort queries by (l_block, r_block, t). Usually block size for l and r is n^{2/3}, and for time we use n^{1/3}? Let's derive properly.
Standard Mo's with updates: We have queries (l, r, t) where t is number of updates before query. We sort queries by (l/B, r/B, t) with B = n^{2/3}. Complexity is O((n+q) * n^{2/3}) if we set B = n^{2/3}. Actually, the typical analysis: There are O((n/B)^2) blocks for (l,r). Time complexity is O((n) * (n/B) * B + q * B + total updates * n / B)? Hmm, I'm mixing.
Let's recall from known resources: For Mo's algorithm with updates, we divide array into blocks of size B (for l). We sort queries by (l_block, r_block, time). The time complexity is O((n+q) * n^{2/3}) if B = n^{2/3}. The total number of movements in l, r, and time is O((n+q) * n^{2/3}). I think it's correct.
But 4.3e8 is large; however, many problems with n=1e5 and Mo's with updates pass if B is chosen appropriately and operations are cheap. But 4.3e8 may be too high for 2 seconds, but perhaps with O(1) operations it could pass if optimized. With O(log n) per add/remove, it's likely too slow.
We can try to reduce operations by using a better DS: we need to maintain active frequencies set. Since the number of distinct frequencies is small (O(√n)), we could maintain the set as a sorted list using insertion sort? But we still need to find whether a frequency becomes zero or appears. Since we have only O(√n) distinct frequencies, we could store cntFreq and also maintain a vector of active frequencies, but we need to insert/delete values from that vector. The active set size is at most ~450, so we could simply use an array of size n? But we need to know which frequencies are active to later iterate for query. However, for updates, we can just update cntFreq and also maintain a boolean array active[f] indicating if cntFreq[f]>0. Since n up to 1e5, we can have an array of bool active[0..n] (or up to max frequency). Then for query, we need to iterate over active frequencies in order. To iterate over active frequencies in sorted order, we could maintain a list (like a vector)