We need to read the problem carefully: Given array a of n integers (1 <= n, k <= 10^5). Need to find a segment [l, r] that satisfies: exactly k distinct numbers in that segment. Additionally, it must be minimal by inclusion: i.e., there is no segment [x, y] that also has exactly k distinct numbers and is strictly inside [l, r] (i.e., l <= x <= y <= r, and (x,y) != (l,r) with shorter length). But note: The segment itself may not be the shortest among all segments with k distinct numbers; it only needs to be such that no proper subsegment of it also has exactly k distinct numbers. In other words, it is a minimal (by inclusion) segment with exactly k distinct numbers. Among possibly many such minimal segments, we can output any.
If no segment has exactly k distinct numbers, output -1 -1.
We need to produce l and r.
Approach: The problem reduces to finding any segment that has exactly k distinct numbers and is minimal by inclusion: meaning that if we shrink it from either left or right (by moving l rightwards or r leftwards), we either lose a distinct number (so distinct count becomes k-1) or break the property (maybe becomes k+1? Actually shrinking cannot increase distinct count, it can only decrease or stay same; moving endpoints inward can remove some numbers, possibly reducing distinct count. For the segment to be minimal, we require that any proper subsegment does not have exactly k distinct numbers. So any immediate shrink from left or right (i.e., [l+1, r] or [l, r-1]) must have distinct count not equal to k (presumably less than k, because shrinking can only decrease distinct count; cannot increase. So they must have < k distinct numbers. Because if they had k distinct numbers, then that would be a smaller segment inside that also has exactly k distinct numbers, violating minimality. So for minimality, we need that both after removing leftmost element (if l<r) the distinct count drops below k, and after removing rightmost element (if l<r) the distinct count also drops below k. If l==r, then it's automatically minimal because no proper subsegment exists (length 1). But then it must have exactly k distinct numbers: length 1 implies distinct count =1. So only if k=1, such a segment could be valid.
But is it necessary that both left shrink and right shrink yield count < k? Consider a segment that has exactly k distinct numbers, but maybe only one side shrinking yields exactly k, while the other yields < k. That would mean there exists a proper subsegment (the one from that side) that also has exactly k distinct numbers, which is a proper subsegment, so the original segment is not minimal. So yes, for minimality, we need that no proper subsegment has exactly k distinct numbers. So both immediate shrinks should yield distinct count ≠ k. Since shrinking reduces distinct count, they would be ≤ k. The only possibility is that they have < k distinct numbers (since they cannot have > k). So both left-shrink and right-shrink must have distinct count < k. That is a necessary condition. Is it sufficient? Not necessarily: there might be a subsegment that is not an immediate shrink but somewhere inside, e.g., remove both ends, but if both immediate shrinks have < k, could there be a subsegment that removes some interior? Wait, if you remove both ends, that is a proper subsegment that is also a subsegment of either left-shrink or right-shrink? Actually, removing both ends yields [l+1, r-1] which is a subsegment of [l+1, r] (which has < k distinct). If [l+1, r] has < k distinct, then any subsegment of it also has ≤ that distinct count, so also < k. So no subsegment can have k distinct. Similarly any subsegment that is a proper subset of [l, r] will be contained either in [l+1, r] or [l, r-1] (or both) because any proper subsegment either excludes left element or excludes right element (or both). Actually, if a proper subsegment is not equal to the whole, then it either does not include element at position l or does not include element at position r (or both). So it is a subsegment of either [l+1, r] or [l, r-1]. Since both of those have < k distinct numbers, any subsegment of them will have ≤ < k, so < k. Thus condition that both immediate shrinks have < k is sufficient. So minimality equivalent to: exactly k distinct numbers in [l, r], and distinct numbers in [l+1, r] < k and distinct numbers in [l, r-1] < k. For l=r, there are no proper subsegments, so condition automatically holds (but must have k=1). But we could also treat as vacuously true.
Thus we need to find any segment with exactly k distinct numbers such that removing leftmost or rightmost element reduces distinct count below k.
Alternatively, we could consider sliding window techniques to find minimal segments. However note that "minimal by inclusion" does not necessarily mean the shortest possible; it's like a "minimal" element in the partially ordered set of segments with property under inclusion. So they are segments that have exactly k distinct numbers, but any smaller subsegment (by shrinking from either side) loses a distinct number (i.e., the count becomes less than k). That implies that both the leftmost element and the rightmost element are "critical" in the sense that they contain the last occurrence of some distinct value within the segment? Let's think: For the segment [l, r] with exactly k distinct numbers, if we remove the leftmost element (a[l]), the distinct count becomes less than k. That means that a[l] is the only occurrence of some distinct value within [l, r]. Similarly, a[r] is the only occurrence of some distinct value within [l, r]. However, note that it's possible that a[l] and a[r] are the same value? If k>1, they cannot be the same? Let's examine: Suppose k=2, segment [l, r] contains values {x, y}. If a[l]=x and a[r]=x, then x appears at least twice (at left and right). Then removing leftmost might still leave x somewhere inside, so distinct count might still be 2 if there is also y present. But could removing leftmost reduce distinct count? If x appears also elsewhere, then after removal, x still appears, so distinct count may remain 2. So to reduce count, we need that a[l] is unique in the segment. Similarly for a[r]. So both endpoints must be unique within the segment. Moreover, because the segment has exactly k distinct numbers, and both endpoints are unique occurrences, those unique values are distinct? They could be the same only if that value appears exactly once and it's both endpoints, implying l=r, i.e., single element, and k=1. So for k>1, a[l] and a[r] must be two distinct values, each appearing exactly once in the segment. Also, any other distinct values (k-2 of them) may appear multiple times, but at least one occurrence each.
So the problem: find a segment [l, r] that contains exactly k distinct numbers, and such that the leftmost element's value occurs exactly once in [l, r], and the rightmost element's value occurs exactly once in [l, r]. (For k=1, any single-element segment works; we can just output any index where the value exists, but note we must ensure that segment has exactly 1 distinct number, which is always true for length 1. But we need minimal by inclusion: length 1 segment is automatically minimal because no proper subsegment. So we can just output any single element. However we need to check: if k=1, is it possible that no segment exists? Since array length >=1, there is at least one element, so a segment of length 1 always has exactly 1 distinct number. So answer exists. However we must be careful: if the problem expects a segment that is minimal by inclusion, and there is also possibility of longer segments with 1 distinct number? But those are not minimal because they contain a smaller subsegment (like a single element) that also has exactly 1 distinct. So the minimal segments are the single elements. So we can output any single element. But the problem may expect a segment that is minimal by inclusion, we can output any such segment. So for k=1, we can simply output "1 1" (or any index). But we need to confirm with examples: not provided.
Now for k>1: need a segment satisfying: exactly k distinct numbers, leftmost value unique within segment, rightmost value unique within segment.
Is that condition sufficient? Let's verify: If leftmost is unique within segment, then removing leftmost eliminates that distinct value, reducing distinct count by 1, thus becomes k-1 < k (since k>1). Similarly for rightmost. As argued earlier, this ensures minimality. Could there be minimal segments where leftmost is not unique but still removing leftmost reduces distinct count? For distinct count to reduce, the leftmost value must appear only once in the segment; if it appears more than once, then after removal, that value still appears, so count may stay the same. It could possibly reduce if the leftmost value is the only occurrence of some value? Wait, if it appears more than once, it's the same value, so the distinct set after removal remains the same (since the value still present). So distinct count cannot decrease if leftmost element's value appears elsewhere in the segment. However, could it decrease because removing leftmost might also affect other values? No, distinct count can only decrease if a value disappears entirely. So leftmost value must be the only occurrence of that value in the segment. So condition holds. Thus minimal by inclusion segments (with length > 1) are exactly those segments with exactly k distinct numbers and whose leftmost and rightmost occurrences are each unique within the segment. For length =1, it's a special case but also satisfies uniqueness of both endpoints (the same element) and exactly k distinct numbers if k=1. So the condition can be unified: segment [l, r] with exactly k distinct numbers, and for both endpoints, the frequency of that value in the segment is 1.
Now, we need to find any such segment efficiently given constraints up to 10^5.
One approach: use two-pointer sliding window to find segments with exactly k distinct numbers. But we need a specific type: leftmost and rightmost unique.
Alternatively, we could try to find all minimal segments by considering each index as potential left endpoint where it's unique, and then expand to include exactly k distinct numbers with the rightmost also unique.
We could attempt: For each position i (1-indexed), consider it as left endpoint if a[i] is the only occurrence of its value in the segment we will find. That means that within segment, no other a[i] appears. So we could look for the next occurrence of a[i] to the right; the segment cannot extend beyond that next occurrence minus 1 because then a[i] would appear again. So the segment's right boundary must be < next occurrence of a[i]. Similarly, the rightmost value must be unique, so the segment's left boundary must be > previous occurrence of the value at r.
But we could also try to find segments that are "minimal" by looking for occurrences where we have a "window" where the set of distinct values is exactly k and the window is "tight" in the sense that shrinking from left or right loses a distinct value. That is like windows that are minimal with respect to distinct count = k. These are essentially the windows found when we slide a window and maintain count of distinct numbers, and we try to shrink from left as much as possible while keeping distinct count = k. If we then shrink one more, we get k-1. That yields a window that is "minimal" from the left side: i.e., if we try to move left pointer rightwards, we reduce distinct count. But does that guarantee that the rightmost element is also unique? Not necessarily. Example: array: 1,2,2,3, with k=2. Consider window [2,4] (2,2,3) has distinct {2,3}=2. If we shrink left from index2 to index3, we get [3,4] (2,3) still distinct 2, so [2,4] is not minimal because [3,4] is a subsegment. The minimal from left approach: start with a window that has >=k distinct, then expand right and shrink left to get exactly k, and then try to shrink left as much as possible while maintaining exactly k. That yields a window where moving left pointer right by one reduces distinct count to k-1. That window has leftmost unique? Possibly yes: because if leftmost value had another occurrence inside, then we could move left pointer to the next occurrence and still keep the distinct count same. Actually, if the leftmost value appears again later, then we could increment left pointer (skip the first occurrence) and the window still contains that value (from the later occurrence), so distinct count remains k. Thus a window where left pointer cannot be moved right without dropping distinct count implies that the leftmost value is unique within the window. Because if there was another occurrence, we could move left pointer to i+1 and still have the same set. So indeed, the condition that shrinking left reduces distinct count is equivalent to leftmost being unique. Similarly, we could have a window where we shrink right as much as possible (by moving r leftwards) while maintaining k distinct numbers. That would give rightmost unique. But a minimal by inclusion segment must satisfy both conditions simultaneously. So we need a window that is both left-minimal and right-minimal.
One simple way: for each possible right boundary, we could try to find the minimal left such that distinct count = k and left is as far right as possible while still having exactly k? Actually, we can use two pointers to maintain a window that has exactly k distinct numbers, and then try to shrink from both ends to make it minimal. But we need both sides to be minimal. Could we find all such minimal windows by a standard approach? Perhaps we can find for each possible left or right the corresponding "tight" window.
Another way: Since constraints are moderate (n up to 1e5), we could perhaps precompute next and previous occurrences and try to find a segment that has exactly k distinct numbers where the left index is the first occurrence of its value after some point? Actually, the condition suggests that the segment is such that its left index is the first occurrence of that value within the segment, and its right index is the last occurrence of that value within the segment. Additionally, there are exactly k distinct values. So the segment's leftmost element must not have any occurrence to its right within the segment. That means that the next occurrence of a[l] (if any) must be > r. Similarly, the previous occurrence of a[r] must be < l.
Thus we could treat each distinct value and consider its positions. For each possible segment defined by the first and last occurrence of a set of k distinct values? Not exactly.
Maybe we can think of it as: we need to pick k distinct values, and for each value we need to select a segment that includes all chosen values? Actually, the segment must contain exactly those k distinct values (no extra). But it could also contain repeated values of those k. So we have exactly k distinct values in the segment.
Now, leftmost value is unique, so within the segment there is exactly one occurrence of that value: at l. That means that the segment does not include any other occurrence of that value. So if we know the positions of each value, the segment [l, r] must be such that for the value v = a[l], the next occurrence of v to the right (if any) is > r, and the previous occurrence is < l (obviously). So l is the last occurrence of v before r? Actually, it's a single occurrence, so there are no other occurrences between l and r.
Similarly, for value w = a[r], there is no other occurrence of w in [l, r] besides r.
Moreover, the segment includes exactly k distinct values. So the set of values present in [l, r] is exactly some set S of size k, with the property that for the leftmost value, it appears only at l, for the rightmost value, it appears only at r, and for the other values (if any) they may appear multiple times.
So maybe we can find a segment by scanning and maintaining counts. One approach: Use two pointers to find a window with exactly k distinct numbers, then try to shrink from both ends as much as possible while keeping exactly k distinct numbers. But careful: The typical two-pointer algorithm for "minimum length substring with exactly k distinct" gives the smallest length window. That window might not satisfy both uniqueness conditions? Actually, the smallest length window with exactly k distinct numbers will indeed have leftmost and rightmost both unique? Let's test: array: 1,2,2,3, k=2. Smallest window with exactly 2 distinct? Could be [1,2] (1,2) length2, leftmost=1 unique? In [1,2], value 1 appears only once, value 2 appears once. Both unique. That's minimal by inclusion? Check immediate shrinks: [2,2]? Actually, [1,2] length2. Shrink left: [2,2] has distinct 1 (just 2) -> less than 2; shrink right: [1,1] distinct 1 -> less than 2. So it is minimal. Another smallest window: [3,4] (2,3) also length2 similarly unique. But what about [2,3] (2,2) distinct count 1, not 2. So smallest window works. But consider array: 1,2,1,3, k=2. Smallest window with exactly 2 distinct numbers? Candidates: [1,2] (1,2) length2, both unique? In [1,2], value 1 appears once, value 2 once => unique; [2,3] (2,1) length2, 2 appears once, 1 appears once => unique; [3,4] (1,3) length2; Also maybe [1,3] (1,2,1) length3 has two distinct numbers but leftmost=1 not unique (appears again at position3). So the smallest length window is length2, which satisfies both uniqueness. So perhaps the minimal length windows always satisfy both uniqueness? Not necessarily: consider k=2, array: 1,2,2,2. The windows with exactly 2 distinct numbers: [1,2] (1,2) length2, both unique; [1,3] (1,2,2) distinct 2, leftmost unique, rightmost not unique (since 2 appears multiple times). That's length3 not minimal length. The minimal length is 2, which is fine. But what if all windows of length exactly k (i.e., length = k) are not possible? Example: k=2, array: 1,1,2. Windows with exactly 2 distinct numbers: [1,3] (1,1,2) length3; [2,3] (1,2) length2? [2,3] (1,2) has values 1 and 2, distinct 2, length2. That window: leftmost=1 (position2) appears also at position1? But within [2,3], there is only one occurrence of 1 (at position2). Because position1 is outside. So within the segment, leftmost is unique. Rightmost=2 appears once. So it satisfies uniqueness. So length2 works. So the minimal length window (shortest) always seems to have both endpoints unique? Let's try to construct a counterexample: Is there a case where the shortest window with exactly k distinct numbers still has a non-unique endpoint? Suppose we have k=3. Array: 1,2,1,3,2. Let's look for a window with exactly 3 distinct numbers. The distinct values are 1,2,3. Shortest window? [1,4] (1,2,1,3) length4: leftmost 1 appears again at pos3, so leftmost not unique. [2,5] (2,1,3,2) length4: leftmost 2 appears again at pos5, not unique. [1,5] all 5 length5. [2,4] (2,1,3) length3: distinct {1,2,3}=3, length3. This window [2,4] (positions 2,3,4): values 2,1,3. leftmost=2 appears only at position2? In the array, there is also 2 at position5, but that's outside. Within the segment, only one occurrence of 2. So leftmost unique. rightmost=3 appears only once. So both unique. So shortest window works.
It appears that any window that is the shortest possible length for its distinct set will automatically have both endpoints unique. Because if either endpoint were not unique, we could shrink the window from that side (by moving the endpoint inward to the next occurrence of that value) and still maintain the same set of distinct values (since that value remains inside), resulting in a shorter window with exactly k distinct numbers. Thus the existence of a shorter window contradicts minimal length. So indeed, the globally minimal length window(s) are minimal by inclusion (they are left-minimal and right-minimal). Therefore, one approach is to find any segment of minimum possible length that has exactly k distinct numbers. Then output that. But careful: The problem does not require the segment to be minimal in length; it just needs to be minimal by inclusion. However, any globally minimal length segment is automatically minimal by inclusion (since if it were not, there would be a proper subsegment with exactly k distinct numbers, which would be shorter, contradicting minimal length). So outputting a minimum-length segment with exactly k distinct numbers is a valid answer. However, we must ensure that such a segment exists if any segment with exactly k distinct numbers exists. That is true: if any segment with exactly k distinct numbers exists, then among them there is at least one of minimum length. That minimum-length segment will be minimal by inclusion. So we can just find the shortest segment satisfying distinct count = k. If multiple, any is fine. And if no such segment exists, output -1 -1.
But is it guaranteed that the shortest segment always satisfies both uniqueness? Yes, as argued: if a segment [l,r] has exactly k distinct numbers and is of minimal length among all such segments, then for any proper subsegment, if it also had exactly k distinct numbers, its length would be less, contradicting minimality. So it's minimal by inclusion. So it's sufficient to output any shortest segment.
Now, we need to find any shortest segment (minimum length) that contains exactly k distinct numbers. This is a classic problem: smallest subarray with exactly k distinct characters. However, typical problems ask for at least k distinct numbers, or exactly k. For exactly k, we can use two pointers / sliding window to find minimal length window containing at most k? Actually, we can adapt: to find minimal length window with exactly k distinct, we can maintain windows with at most k distinct and track? Another approach: use two pointers to find for each left the minimal right such that distinct count >=k, then expand? Actually we need exactly k. Standard method: For each left, find the smallest r such that window [l, r] has at least k distinct, then if it's exactly k, try to shrink from right as much as possible while keeping exactly k? But that would give a window that is left-minimal but not necessarily right-minimal? However, if we then find the minimal length overall by iterating left and adjusting right, we can compute min length. More directly, we can do sliding window to count distinct, and when we have exactly k, we try to shrink from left while maintaining exactly k? That gives windows that are left-minimal but not necessarily right-minimal. But to get the overall minimal length, we can record length when we have exactly k and then move left to reduce length while keeping exactly k? Actually, typical algorithm for smallest subarray with exactly K distinct: use two pointers to maintain window with exactly K distinct by expanding right and then when we have exactly K, we try to move left as far as possible while still having K, then record length, then move left one step to drop one distinct, and continue. That yields windows that are left-minimal (i.e., after moving left as far as possible while keeping K, left is unique). But the length recorded at that point is not necessarily the globally minimal length? Actually, as we slide, we consider each possible right endpoint, and for each, we find the minimal left that yields exactly K distinct, which gives a window that is left-minimal. Among those windows, the one with smallest length is indeed globally minimal. So we can implement that.
But careful: The typical algorithm works for "at most K" or "at least K". For exactly K, we can use the approach: maintain a window with at most K distinct, but that's not directly. Let's design:
We'll maintain two pointers L=0 (or 1), and a frequency map. We'll move R from 1 to n, adding a[R], increasing count. While number of distinct > K, we move L forward, decreasing frequencies, until distinct <= K. At any point when distinct == K, we have a candidate window. But that window may not be minimal from the left side because there could be extra repeated elements at the left that could be removed without reducing distinct count. To get the minimal length for this R, we would want to shrink L as far as possible while maintaining distinct == K. So after we have distinct == K, we can try to increment L while distinct remains K (by checking if the element at L has frequency >1, so removing it doesn't drop distinct). Actually, we can do: when distinct == K, while freq[a[L]] > 1, we can decrease freq and move L++. This will shrink the window while keeping distinct == K. Then we have a window that is left-minimal (cannot shrink left without losing a distinct). But note that this window is not necessarily right-minimal, but we are only concerned about length. The resulting window after shrinking left as much as possible will be a candidate. Its length is (R-L+1). We can track minimal length and the corresponding L,R.
After recording candidate, we then move L one step forward to reduce distinct to K-1 (by removing an element that is necessary because after shrinking left as much as possible, the leftmost element is unique). Actually, after shrinking, we have a window where leftmost is unique. To proceed to next R, we can increment L by 1 to drop that unique element, making distinct = K-1. Then we continue with R. But careful: If we move L forward by 1, we may break the invariant distinct maybe K-1, and we will later expand R to possibly get back to K. This is a standard algorithm for "exactly K distinct" minimal window. But we don't need to strictly follow that; we can just for each R, after adjusting L to maintain distinct <= K, if distinct == K, then we attempt to shrink L while possible (freq[a[L]] > 1) to get left-minimal window, record length, and then we can simply continue without moving L further? However, to make sure we explore all possibilities, we can just after recording, we move L one step (increment by 1) and continue. This ensures that we don't get stuck because the window would remain at K if we don't move L? Actually, if we don't move L, the window will stay with distinct possibly still K as R increases, but we might miss some candidates? The standard approach uses two phases: first expand R, then when distinct > K, move L. Then when distinct == K, record candidate after optionally shrinking L. Then to continue, we move L one step to reduce distinct to K-1, then keep R moving. This ensures that we consider all windows with exactly K distinct. It's similar to the algorithm for "minimum window substring" for exactly K distinct characters.
But we can also do a simpler O(n) approach: For each left index, find the smallest right such that distinct == K. But that would be O(n^2) if done naively. However, we can use two pointers to maintain that as left increases, right moves forward. That's like: maintain window with exactly K distinct while moving left. But it's tricky because when we move left, the distinct count might drop below K, so we need to move right to bring it back. That is also O(n). Let's design a clear algorithm:
Initialize left = 1, right = 1, freq = empty, distinct = 0.
Let min_len = INF, best_l, best_r.
While right <= n:
Add a[right] to freq.
If freq[a[right]] == 1: distinct++.
While distinct > K:
remove a[left] from freq: freq[a[left]]--; if freq[a[left]] == 0: distinct--; left++.
If distinct == K:
// Now we have a window with exactly K distinct.
// Try to shrink from left as much as possible without reducing distinct.
while freq[a[left]] > 1:
freq[a[left]]--; left++;
// Now left is minimal for this right (leftmost unique).
// Record window.
if (right - left + 1) < min_len:
min_len = right - left + 1; best_l = left; best_r = right.
// After recording, we need to move left forward by 1 to allow next windows.
// Because if we keep left as is, the window will still have K distinct as we increase right,
// but we would be considering larger windows than necessary; but we already recorded the minimal for this left? Actually, we could also keep left and increase right, but those windows would be larger and not beat min_len. However, to explore all possibilities, we can just continue without moving left. But then we might miss windows where a different left yields a smaller length? But those windows would be discovered when we eventually move left? The algorithm that doesn't move left after recording might still work because later as right increases, the window may still have K distinct, and we will again try to shrink left. However, the shrinking step might not be able to shrink left because the leftmost may still be unique. So if we don't move left, we will keep recording the same window (or larger) but not smaller. Actually, we need to eventually move left to allow windows with a different left. So we must move left at some point. The standard technique is: after recording, we remove the leftmost element (by moving left forward by 1) to break the K distinct condition, so that we can later find new windows with K distinct. If we don't, we may stay in a state where distinct == K and later as we add new elements, distinct may become > K, then we will move left again. But we could still explore other left values. However, the algorithm could become O(n) still? Possibly, but we might miss windows where the left is between current left and future left? Let's test: Suppose we have window [l, r] with exactly K, and we shrink left to l_min. Then we record. If we don't move left, then as r increases, we will have window [l_min, r+1]. It might still have exactly K if the new element is one of the existing distinct values. But we will again try to shrink left while possible. However, since we didn't move left, the leftmost element may still be unique, so we cannot shrink; we would record [l_min, r+1] which is longer, not interesting for min length. Eventually, when the new element introduces a new distinct value, distinct becomes K+1, we will start moving left until distinct <= K, possibly moving left past the original l_min. This will eventually consider other left values. So not moving left may still be fine, because the window will eventually move left when distinct > K. However, there is a scenario: after shrinking left, we have l_min such that a[l_min] is unique. Now if we add a new element that is equal to a[l_min], then distinct remains K, but now a[l_min]'s frequency becomes 2, so we can shrink left further! That could potentially yield a shorter window than previously recorded for this right? But if we added an element equal to the leftmost, then the leftmost value is no longer unique; we could shrink left by moving it rightwards until the leftmost is unique again. That could reduce length further. So we would want to capture that. In our algorithm, if we don't move left, we will later when we have distinct == K again (which it already is) we will perform the while loop to shrink left (while freq[a[left]] > 1). So it will shrink left further. So we will capture the potentially smaller window. So not moving left after recording might still work; the algorithm would continue to process each right, and for each right where distinct == K, we try to shrink left as much as possible, then record. This is essentially doing: for each right, find the minimal left such that window [left, right] has exactly K distinct. And then track the minimal length over all right. That is a valid approach: for each right, we need to find the smallest left (i.e., the largest left) such that the window contains exactly K distinct. But we need to maintain a data structure that allows us to know, for current right, the minimal left that yields exactly K distinct. The typical method to compute that in O(n) is to have a left pointer that we move as right increases, but we need to ensure that for each right we get the appropriate left. If we just keep a single left pointer and update it when distinct > K, and then while we can shrink left (freq[a[left]]>1) we shrink, then for each right we will have a left that is the minimal left for the current right? Let's test this logic.
We maintain left, initially 1. We iterate right from 1 to n. We add a[right]. Then while distinct > K, we remove a[left] and left++. After that, if distinct == K, we then while freq[a[left]] > 1 (i.e., the leftmost element appears more than once), we remove it and left++. This yields a window where leftmost is unique, and distinct == K. Is this left guaranteed to be the minimal left for this right? Could there be a larger left (i.e., window starting later) that also yields exactly K distinct and is shorter? The minimal left for a given right that yields exactly K distinct would be the largest left such that [left, right] still has exactly K distinct. Because the left cannot be increased beyond that without dropping a distinct. So the minimal left is exactly the leftmost index such that after that, if we move left any further, we lose a distinct. That is precisely the condition after shrinking: leftmost is unique. So yes, after the shrinking step, left is the minimal left for that right. So the window [left, right] is the shortest possible for that right (with left maximal). So its length is right-left+1. So for each right, we compute that length if distinct == K, and keep global minimum.
But we need to be careful: After we shrink left for a given right, we don't reset left for next right. We continue with the same left pointer. However, when we move right to right+1, we add a new element. At that point, the left pointer is still at the position from previous step. This left might be too far left? Actually, after shrinking, left is the minimal left for previous right. For the new right, the window [left, new_right] might contain K distinct, but could also have more? Or less? Let's examine transitions.
Suppose we have right = r, after processing we have left = l_r (minimal left for r). Then we move to r+1. We add a[r+1]. The distinct count may increase, stay same, or even if new value is new, distinct may become K+1. If distinct becomes > K, we will enter the while loop to move left forward until distinct <= K. That's fine. If distinct stays <= K, we then check if distinct == K. If distinct == K, we then perform shrinking while freq[a[left]] > 1. But note: The left pointer from previous iteration may not be minimal for r+1 because maybe we could move it further right (increase left) while still keeping K distinct. That's exactly what the shrinking step does: while the leftmost element appears more than once (freq > 1), we can move left forward without losing distinct. But also, it's possible that the leftmost element appears only once, so we cannot move left further. So the shrinking step will again bring left to the minimal position. So this algorithm works as we progress right, adjusting left appropriately, and for each right where distinct == K, we compute the minimal left for that right and record length.
The only potential issue: When distinct becomes less than K after adding a new element? That can't happen because adding an element cannot reduce distinct. So distinct only increases or stays same. So if we had distinct == K before adding, after adding, distinct >= K. Actually, distinct could stay K if the new element is already seen. So distinct can be K or K+1 after addition. If distinct becomes K+1, we then while distinct > K we move left. That may reduce distinct to K or even less. But if distinct becomes less than K after moving left? Possibly, if we move left too far? The while condition is while distinct > K, we move left. After moving left, distinct may become exactly K or less? Since we stop when distinct <= K. So it could become < K. In that case, we won't record for this right because distinct != K. That's fine.
Now, does this algorithm guarantee that for each right, the left we compute (if distinct==K) is indeed the minimal left for that right? Let's reason more formally.
We maintain left pointer L and frequencies for window [L, R] (inclusive). At each step after processing R, we ensure that the window [L, R] satisfies distinct <= K (by the while loop). Also, we then try to shrink L as far as possible while maintaining distinct == K, but only if distinct == K. However, note that after the while loop for distinct > K, we have distinct <= K. If it's exactly K, we then shrink L while freq[a[L]] > 1. This ensures that the leftmost element's count is 1, so it's unique. Could there be a scenario where we can also shrink L by more than one step even if freq[a[L]] == 1? No, because if freq[a[L]] == 1, moving L forward would remove that unique element, reducing distinct to K-1, so we cannot shrink further while keeping K distinct. So L is indeed the maximal left such that window has exactly K distinct (i.e., the leftmost index that we cannot increment without losing a distinct). So it's the minimal length window for that right.
Now, what about the case where distinct < K? We don't record anything. That's fine.
Now, does this algorithm explore all possible windows with exactly K distinct? Typically, yes, because for any window [l, r] with exactly K distinct and left minimal (i.e., l is maximal such that window still has K distinct), there will be a step when r is processed where L becomes exactly l. Because as we expand r, L moves accordingly. This is standard sliding window for exactly K distinct. So we will capture at least one minimal-length window overall.
Thus we can compute min_len and corresponding l,r. If min_len remains INF, output -1 -1; else output best_l, best_r.
But we must double-check edge cases: k=1. For k=1, we need minimal length segment with exactly 1 distinct. The smallest possible is length 1. Our algorithm: we maintain window with distinct <=1. For each R, we add a[R]. If distinct becomes >1, we move L until distinct <=1. Then if distinct ==1, we shrink L while freq[a[L]] > 1? Actually, with distinct ==1, the while condition while freq[a[L]] > 1 will be: Since we have only one distinct value, its frequency is the window length. So freq[a[L]] will be >=1. If window length > 1, then freq[a[L]] > 1 because the only value appears multiple times. So the while loop will shrink L as much as possible until only one occurrence remains (freq[a[L]] == 1). That reduces the window to a single element (the rightmost occurrence? Actually, after adding many same numbers, the shrinking step will move L until the window contains only the most recent element? Let's simulate: array: 1,1,1,1. k=1. R=1: add 1, distinct=1, while freq[a[L]]>1? freq[1]=1, so not. Record length1, best becomes (1,1). R=2: add 1, distinct still 1 (since same), after addition distinct=1, but distinct>k? No. Then while loop for >k not triggered. Then if distinct==1, we try to shrink: freq[a[L]] = freq[1] = 2 >1, so we remove a[L] (position1), L=2, freq[1] becomes 1. Now window [2,2], length1, record. So we get length1 again. So best remains length1. So algorithm yields min_len=1. That's fine. So we can output any length-1 segment; our best_l,best_r will be the last one recorded? Actually we track min_len; if multiple with same min_len, we keep the first encountered or whichever. That's fine.
Another edge case: k > number of distinct in whole array. Then no window with exactly k distinct exists. Our algorithm will never record a candidate, min_len INF, output -1 -1.
Another edge case: Suppose there is a window of length 2 with exactly k distinct, but also a window of length 1? That's only possible if k=1, then length1 possible. So for k>1, min_len >= k obviously, but our algorithm will find it.
Now, is it guaranteed that any minimum-length window is minimal by inclusion? Yes, as argued earlier. However, we must be careful about the case when k=1 and array has many 1's. The minimum-length window is length 1. That segment is minimal by inclusion because it has no proper subsegments. So correct.
Now, check the sample:
Sample1: n=4, k=2, array: 1 2 2 3.
Let's simulate algorithm:
Initialize L=1, freq={}, distinct=0, min_len=INF.
R=1: a=1. freq[1]=1, distinct=1. distinct<=2, not >. distinct==2? no. So no record.
R=2: a=2. freq[2]=1, distinct=2. distinct not >2. distinct==2 yes. Now shrink: while freq[a[L]]>1? L=1, a[L]=1, freq[1]=1, not >1. So window [1,2] length=2. Record min_len=2, best=(1,2).
R=3: a=2. freq[2]=2, distinct=2 (still). distinct==2. Shrink: L=1, a[L]=1, freq[1]=1, not >1; so window [1,3] length=3, not better.
R=4: a=3. freq[3]=1, distinct=3. distinct>2 => while distinct>2: remove a[L]=1: freq[1]=0, distinct=2 (since 1 gone, distinct reduces to 2? Actually, after removal distinct becomes? Values present: 2 (freq 2), 3 (freq 1) => distinct=2). Now distinct=2 <=2, stop while. distinct==2 yes. Shrink: L currently 2? After removing L=1, L becomes 2. Now check while freq[a[L]]>1: a[L]=2, freq[2]=2 >1 => remove a[L] (2 at pos2): freq[2]=1, L=3. Now freq[a[L]]? a[L]=2, freq[2]=1 not >1. So window [3,4] length=2. That equals min_len=2, could update or not. Our algorithm might update if we use <, so not update if equal; we keep earlier (1,2). That's fine. Output (1,2) matches sample.
Sample2: n=8, k=3, array: 1 1 2 2 3 3 4 5
Simulate:
R=1: add 1, distinct=1.
R=2: add 1, distinct=1.
R=3: add 2, distinct=2.
R=4: add 2, distinct=2.
R=5: add 3, distinct=3. distinct==3 => shrink: L=1, a[1]=1, freq[1]=2>1 => remove, L=2, freq[1]=1. Now check: a[2]=1, freq[1]=1 not >1, stop. window [2,5] length=4. Record min_len=4, best=(2,5).
R=6: add 3, distinct=3. Now window initially [2,6] (after addition). Shrink: L=2, a[2]=1, freq[1]=1 => cannot shrink; window length=5, not better.
R=7: add 4, distinct=4 >3 => while distinct>3: remove a[2]=1: freq[1]=0, distinct reduces to 3? Actually after removal, values: 2 (freq2?), 3 (freq2?), 4 (freq1). Let's compute frequencies before removal: after adding 4 at R=7, we have window [2,7] includes: positions 2:1, 3:2,4:2,5:3,6:3,7:4. freq: 1:1, 2:2, 3:2, 4:1 => distinct=4. Remove a[2]=1: freq1 becomes 0, distinct becomes 3 (now values 2,3,4). L becomes 3. distinct=3 <=3, stop while. Now distinct==3, shrink: L=3, a[3]=2, freq[2]=2>1 => remove, L=4, freq[2]=1. Now a[4]=2, freq[2]=1 not >1. So window [4,7] length=4. min_len=4 remains; could keep (2,5) or update to (4,7). Not better.
R=8: add 5, distinct=4 >3 => while distinct>3: remove a[4]=2: freq[2] becomes 0? Actually before removal: window currently L=4? Let's track precisely: After previous step, L=4, window [4,7]. Add R=8, a[8]=5. freq update: 5:1. Now window [4,8] includes positions: 4:2,5:3,6:3,7:4,8:5. freq: 2:1? Actually 2 appears only at pos4 (since we removed earlier? After previous shrink we had L=4, freq[2]=1. Adding 5: freq: 2:1, 3:2, 4:1, 5:1 => distinct=4. While distinct>3: remove a[L]=a[4]=2: freq[2]=0, distinct becomes 3 (3,4,5). L=5. Now distinct=3, stop. Shrink: L=5, a[5]=3, freq[3]=2>1 => remove, L=6, freq[3]=1. Now a[6]=3, freq[3]=1 not >1. Window [6,8] length=3. That's length 3, which is less than min_len=4. Update min_len=3, best=(6,8). So algorithm would output (6,8). But sample output is (2,5). Both are minimal by inclusion? Let's check: segment [6,8] (positions 6:3,7:4,8:5) has distinct {3,4,5}=3, length 3. Is it minimal by inclusion? Leftmost=3 appears only once in segment? In [6,8], value 3 appears only at pos6 (since pos5 has 3 but is outside), so leftmost unique. Rightmost=5 appears only once. So it's minimal. Indeed length 3 is shorter than length 4. So [6,8] is a shorter segment, so it is a better candidate for minimal length. The problem says we can output any correct answer; they gave (2,5) as an example, but that does not mean it's the only answer. So (6,8) would also be correct. However, note that the sample output is (2,5). The problem statement: "If there are multiple correct answers, print any of them." So both are acceptable. Our algorithm would output (6,8) if we update when length < min_len, but it might output (2,5) if we use <=? It's fine either way.
But we must check: Is [6,8] indeed a valid minimal by inclusion segment? Yes, exactly. So our algorithm yields a correct answer. So it's fine.
Sample3: n=7,k=4, array: 4 7 7 4 7 4 7. Distinct numbers: only 4 and 7, total distinct =2 <4, so no segment with 4 distinct numbers. Our algorithm will never record a candidate, min_len INF, output -1 -1. matches.
Thus the algorithm works.
Now, we must confirm that the condition "minimal by inclusion" is exactly that the segment cannot be shrunk from either side without losing a distinct number, i.e., both endpoints are unique. And we argued that the minimum-length segment always satisfies this. However, is it possible that there is no minimum-length segment? If there exists any segment with exactly k distinct, then there is a minimum length (since lengths are positive integers bounded below by 1, and finite number of segments? Actually number of segments is O(n^2), but we can have arbitrarily long lengths, but the minimum length exists because the set of lengths is a non-empty subset of positive integers, and it has a minimum. So yes.
But careful: The minimum length segment might not be unique, but it's okay. Our algorithm will find one.
Now, we must also consider corner cases: k=0? The problem constraints: k >= 1 (since 1 ≤ n, k ≤ 10^5). So no need.
Now, we should implement sliding window with frequency array or hash map. Since ai up to 1e5, we can use array of size maybe 200000? Actually a_i up to 10^5, so we can use a freq array of size max_a+1 = 100001, which is fine. But note n up to 10^5, so using array is efficient. However, if a_i can be up to 10^9? The problem says 1 ≤ ai ≤ 10^5. So fine.
Implementation details:
- Input n, k.
- Read array a (1-indexed maybe).
- Initialize freq array of size MAX_A+1 (maybe 100001) all zeros.
- left = 1, distinct = 0, min_len = n+1 (or INF), best_l = -1, best_r = -1.
- Loop right from 1 to n:
- val = a[right]
- freq[val]++
- if freq[val] == 1: distinct++
- while distinct > k:
- left_val = a[left]
- freq[left_val]--
- if freq[left_val] == 0: distinct--
- left++
- if distinct == k:
// Shrink left while possible
while freq[a[left]] > 1:
freq[a[left]]--
left++
// Now window [left, right] is candidate
cur_len = right - left + 1
if cur_len < min_len:
min_len = cur_len
best_l = left
best_r = right
// After recording, we could optionally move left one step to consider next windows? Not required, but the algorithm as described will continue without moving left. However, we might have a situation where we stay in the same state and later when we add new elements, we may get the same window but longer, but it's fine. However, there is a nuance: after we shrink left to make leftmost unique, we might want to move left one step to break the exact k condition to avoid infinite loop? No, there is no loop; we just go to next right. But is it necessary to move left to ensure we don't miss some windows? Let's test a scenario where not moving left could cause us to not consider some windows that would give a smaller length later.
Consider array: [1,2,1,3], k=2. Let's simulate with algorithm that does NOT move left after recording.
Initialize left=1, freq empty, distinct=0.
R=1 (1): add 1, distinct=1.
R=2 (2): add 2, distinct=2. distinct==2, shrink: while freq[a[left]]>1? left=1, a[1]=1, freq[1]=1 => not shrink. record len=2, min_len=2, best=(1,2). (We have L=1,R=2)
R=3 (1): add 1, freq[1]=2, distinct=2. distinct==2, shrink: while freq[a[left]]>1? left=1, a[1]=1, freq[1]=2 >1 => remove, L=2, freq[1]=1. Now check again: left=2, a[2]=2, freq[2]=1 not >1. record len=2 (window [2,3]? Actually after shrinking, L=2, R=3, values 2,1 length2). cur_len=2, not <2, so min_len remains 2, maybe update if we allow equal? Not necessary. So we have (1,2) still.
R=4 (3): add 3, freq[3]=1, distinct=3 >2 => while distinct>2: remove a[left] (left=2, a[2]=2): freq[2]-- from 1 to 0, distinct becomes 2 (values 1 and 3), L=3. Now distinct==2, shrink: left=3, a[3]=1, freq[1]=2 >1 => remove, L=4, freq[1]=1. Now window [4,4]? Actually after shrinking: L=4, R=4, values 3 only? Wait, check: after while distinct>2, we removed element at L=2 (value 2), distinct becomes 2 (values 1 (freq2),3 (freq1)). L becomes 3. Then we do shrink while freq[a[left]]>1: left=3, a[3]=1, freq[1]=2 >1 => remove a[3] (value1), freq[1] becomes1, L=4. Now left=4, check condition again: a[4]=3, freq[3]=1 not >1. So window is [4,4], length1? But distinct count? After shrinking, we need to ensure distinct is still 2. Let's recompute frequencies: after removing a[2] and a[3], we have: freq[1]=1? Wait, we had freq[1]=2 after adding position3 and 1? Let's track carefully:
Initial after R=3: L=2 (after shrink), window [2,3] with freq: a2=2? Actually after R=3, before shrink we had window [1,3]? Let's step properly.
Better to simulate from scratch with algorithm that does shrink after each R, but not forced move left.
I'll simulate step by step with code:
Initialize left=1, freq all zero, distinct=0.
R=1 (a=1):
freq[1]=1, distinct=1.
distinct>k? no.
distinct==k? no.
R=2 (a=2):
freq[2]=1, distinct=2.
distinct>2? no.
distinct==2? yes.
while freq[a[left]]>1: left=1, a[1]=1, freq[1]=1 -> false.
record: len=2, best=(1,2).
(Now left=1)
R=3 (a=1):
freq[1]=2, distinct remains 2 (since 1 already present).
distinct>2? no.
distinct==2? yes.
while freq[a[left]]>1: left=1, a[1]=1, freq[1]=2>1 -> true: freq[1]-- becomes1, left=2.
now check again: left=2, a[2]=2, freq[2]=1 -> false.
record: len = 3-2+1=2, window [2,3], which is length2. (cur_len=2, not <2 so maybe keep previous best)
(Now left=2)
R=4 (a=3):
freq[3]=1, distinct=3.
distinct>2? yes -> while distinct>2:
left_val = a[2]=2, freq[2]-- from1 to0, distinct-- becomes2, left=3.
Now distinct=2 <=2, exit while.
distinct==2? yes.
while freq[a[left]]>1: left=3, a[3]=1, freq[1]=1? Wait, what is freq[1] currently? After previous steps, after R=3 we had left=2. Frequencies: we had after R=3, after shrink: window [2,3] -> freq[2]=1, freq[1]=1. Then we added a[4]=3, so freq[3]=1, freq[2]=1, freq[1]=1 => distinct=3. Then we removed left=2 (value2): freq[2]=0, distinct=2, left=3. Now frequencies: freq[1]=1, freq[3]=1. So distinct=2, left=3, window [3,4] (values 1,3). Now shrink while freq[a[left]]>1: left=3, a[3]=1, freq[1]=1 -> false. So record: len = 4-3+1=2, window [3,4], length2. That's also minimal. So we have found multiple length2 windows. The algorithm found [2,3], [3,4] as well. So it's fine.
Thus, not moving left after recording still captures all minimal windows. So we can keep the algorithm as described.
But there is a nuance: After we shrink left for a given right, we have left at the minimal position. For the next right, if the new element is one that already exists, we might be able to shrink left further (as seen). That's handled.
Thus the algorithm is correct and runs in O(n) time.
Now, we must also consider the case where there might be a segment of minimal length that is not discovered because we never shrink left after the while distinct > K step? But we do the shrink step only when distinct == K. However, could there be a situation where after the while distinct > K step, we have distinct < K? Then we don't record. That's fine.
One more test: k=2, array: [1,2,3,2,1]. The minimal length window with exactly 2 distinct numbers? Possibly [2,3] (2,3) length2, or [3,4] (3,2) length2. Let's simulate algorithm:
R1: add1, distinct=1
R2: add2, distinct=2 -> shrink? freq[1]=1, no shrink -> record (1,2) len2.
R3: add3, distinct=3 >2 -> while distinct>2: remove left=1 (1), distinct=2 (values 2,3), left=2. Now distinct==2 -> shrink: left=2, a2=2, freq[2]=1? freq[2] initially 1? Actually after removal, freq: 2:1,3:1. So freq[2]=1, can't shrink. record (2,3) len2.
R4: add2, freq[2]=2, distinct=2 (still) -> shrink: left=2, a2=2, freq[2]=2>1 -> remove a2, left=3, freq[2]=1. Now left=3, a3=3, freq[3]=1 -> record (3,4) len2.
R5: add1, freq[1]=1, distinct=3 -> while distinct>2: remove left=3 (a3=3), freq[3]=0, distinct=2 (values 2,1), left=4. Now distinct==2 -> shrink: left=4, a4=2, freq[2]=1? Wait after removal, freq[2]=1 (from earlier), freq[1]=1. So freq[2]=1, can't shrink. record (4,5) len2.
Thus all length2 windows found.
So algorithm works.
Now, verify that the found segment indeed has exactly k distinct numbers. Yes.
Now, edge case: k = number of distinct values in whole array, and the whole array may be the only segment? But there may be smaller segments containing all distinct values? Possibly if the array contains all distinct values, then the minimal length window containing exactly all distinct values (which is the number of distinct values, maybe less than n) could be shorter than whole array. Example: array: 1,2,3,1,2,3, k=3. Minimal length window with exactly 3 distinct numbers is length3 (e.g., positions 1-3 or 4-6). So algorithm will find length3.
Now, check scenario where there is a window with exactly k distinct numbers but the minimal length window might be something that does not have both endpoints unique? But we argued that if it's minimal length, then both endpoints must be unique. Formal proof: Suppose [l,r] is a shortest window with exactly k distinct numbers. If a[l] appears elsewhere in [l,r], say at position p > l, then consider window [p, r]. Since a[l] appears again at p, the set of distinct numbers in [p, r] is still k (because a[l] is still present, and no new distinct added), and length is r-p+1 < r-l+1, contradiction. Similarly for a[r]. So indeed both endpoints are unique.
Thus, our approach of finding the shortest window works.
However, we should also consider if there might be cases where the shortest window is not minimal by inclusion? That would be contradictory as we just reasoned. So it's fine.
Now, complexity: O(n) time, O(maxA) or O(n) space for frequencies using array or hashmap.
Implementation:
We'll read n,k. Then read array a (size n). Use 0-indexed for simplicity, but output 1-indexed.
We'll maintain freq array of size maybe 100001 (since a_i ≤ 100000). But note that n may be up to 100k, and a_i up to 100k, so array is fine.
Initialize:
int left = 0;
int distinct = 0;
int min_len = n+1;
int best_l = -1, best_r = -1;
vector freq(100001, 0); // or global array.
Loop right from 0 to n-1:
int val = a[right];
if (freq[val] == 0) distinct++;
freq[val]++;
while (distinct > k) {
int lval = a[left];
freq[lval]--;
if (freq[lval] == 0) distinct--;
left++;
}
if (distinct == k) {
// shrink left while possible (freq[a[left]] > 1)
while (freq[a[left]] > 1) {
freq[a[left]]--;
left++;
}
int cur_len = right - left + 1;
if (cur_len < min_len) {
min_len = cur_len;
best_l = left;
best_r = right;
}
}
}
After loop, if best_l == -1: print "-1 -1"
else: print best_l+1 and best_r+1 (1-indexed).
But we must be cautious: The shrinking step modifies the frequencies and left pointer. After we shrink, we record the candidate. Then we continue to the next right. However, the frequencies and left pointer after shrinking are used for the next iteration. That's okay.
Now, consider if after shrinking we have left such that freq[a[left]] == 1. Then we go to next right. When we add a new element, it may be equal to a[left], making freq[a[left]] become 2, allowing us to shrink again later. That's fine.
Now, check for potential off-by-one: In the shrink step, we are using while (freq[a[left]] > 1). But note: after the while loop that handles distinct > k, it's possible that left > right? Not possible because distinct > k only when window has at least k+1 distinct, so window length at least k+1, so after removal we might still have left <= right. However, if k=0 (not allowed) it could happen. So fine.
Now, test with a case where the array has many distinct numbers and k is large but there is a window.
Edge: k= n (but n up to 1e5). If k = n, then we need exactly n distinct numbers in the window, which implies the window must contain all n distinct numbers. The number of distinct numbers in the whole array could be less than n, so may not exist. If the whole array has exactly n distinct numbers (i.e., all elements are distinct), then the minimal length window with exactly n distinct numbers is the whole array itself (since any subsegment would miss some distinct). So min_len = n. Our algorithm: As we expand right, we will eventually have distinct = n at right=n. Then we will shrink left while possible: but if all elements are distinct, then freq[a[left]] = 1 always, so no shrink. So candidate length = n. That's correct.
Edge: k=1 and array has all distinct. The minimal length is 1. Our algorithm will find a window of length 1 at the first occurrence. It works.
Now, potential pitfalls: The frequency array size: a_i max = 100000 as per constraints. But we can also use unordered_map to be safe if values can be up to 1e9? But given constraints, array is fine. However, some Codeforces problems may have a_i up to 10^9, but here it's specified ≤ 10^5. So okay.
But also note that n can be up to 10^5, and we use O(n) algorithm.
Now, we must also consider if there is any case where the minimal length segment is not found because we never shrink left after the while distinct > K step? Actually, we do shrink when distinct == K. However, consider a scenario where after processing while distinct > K, we end with distinct < K. Then no candidate. That's fine.
Now, consider a scenario where after processing while distinct > K, we have distinct == K, but then we shrink left to make it left-minimal. That's done. Good.
Now, we must ensure that the shrink step does not overshoot and make distinct < K. Because we shrink only while freq[a[left]] > 1, i.e., we remove leftmost element only if it appears at least twice in the window. Removing such an element does not change distinct count because that value still appears at least once. So distinct remains K. So it's safe.
Now, let's test with more complex data:
Case: n=10, k=3, a = [1,2,1,2,3,2,1,2,3,4].
We want minimal window with exactly 3 distinct. It might be [3,5]? positions 3,4,5: 1,2,3 length3? Actually positions: 3:1,4:2,5:3 => distinct 3 length3. So minimal length=3. Our algorithm should find it.
Simulate quickly:
R=1: 1 -> distinct1
R=2: 2 -> distinct2
R=3: 1 -> distinct2? actually distinct still 2 (1,2). So distinct=2.
R=4: 2 -> distinct2.
R=5: 3 -> distinct3 => after addition distinct=3. while distinct>3? no. shrink: left=1, a[1]=1 freq[1]=2 >1 -> remove, left=2, freq[1]=1. Check: left=2 a[2]=2 freq[2]=2 >1? Actually freq[2] currently? After adding positions 1-5, freq:1:2,2:2,3:1. So at left=2, a[2]=2 freq[2]=2>1 -> remove, left=3, freq[2]=1. Now left=3 a[3]=1 freq[1]=1 not >1. So window [3,5] length=3. Record min_len=3. So works.
Now, consider if there is a window with exactly k distinct but the leftmost unique condition holds, but the rightmost may not be unique, but the window is not of minimal length, but it's still minimal by inclusion? Wait, earlier we argued minimal by inclusion requires both endpoints unique. So a window with exactly k distinct but where rightmost is not unique cannot be minimal by inclusion because you could shrink from the right and still have k distinct. So such a window is not minimal. So our algorithm will never output such because it always shrinks left to unique left, but it does not shrink right. However, our candidate windows after shrinking left have left unique, but we haven't ensured right uniqueness. Could it be that after shrinking left, the rightmost element is not unique, but the window length is not the overall minimal length? The window we record may have rightmost not unique, but still be a candidate because we might record it if it's shorter than previously found ones? But could such a window be of minimal length? If it's of minimal length, then by earlier argument both endpoints must be unique. So any window that is globally minimal length automatically has both unique. But if we record a window that is not globally minimal (i.e., larger than the minimal), it could have left unique but right not unique. However, we only keep track of the smallest length found so far. As we iterate, we will eventually find the minimal length, which will have both unique. But suppose there is a scenario where the first candidate we record has length L, which is not globally minimal (because later we find a smaller length). That first candidate could have right not unique? Let's see: In our algorithm, after we have distinct == k, we shrink left to make left unique, but we don't shrink right. So the window we record may have rightmost not unique. Could that happen? Yes, e.g., array: 1,2,1,2,1, k=2. Let's simulate:
R=1: 1 distinct1.
R=2: 2 distinct2 -> shrink? left=1, a1=1 freq1=1 -> no shrink. record [1,2] length2, rightmost=2 unique? In [1,2], 2 appears once -> unique. Actually both unique because length2.
R=3: 1 -> distinct2, shrink: left=1, a1=1 freq1=2>1 -> remove, left=2, freq1=1. Check left=2, a2=2 freq2=1 -> record [2,3] length2, rightmost=1 unique? in [2,3] values 2,1 -> both appear once so unique.
R=4: 2 -> distinct2, shrink: left=2, a2=2 freq2=2>1 -> remove, left=3, freq2=1. left=3 a3=1 freq1=2? Actually after removal, freq1=2? Let's compute: after adding 4th: before shrink, window currently [2,4] with freq: position2:2, pos3:1, pos4:2 => freq2=2, freq1=2? Wait pos3 is 1, pos4 is 2, so freq1=1? Actually we had earlier: after R=3 we had left=2, window [2,3] with freq2=1, freq1=1. Then add R=4 (value 2): freq2 becomes 2, freq1 remains 1, distinct=2. Then shrink: left=2 (value2) freq2=2>1 -> remove, left=3, freq2 becomes1. Now window [3,4] with values 1,2. Both appear once? Actually pos3=1, pos4=2, so freq1=1, freq2=1. So rightmost=2 unique. So again both unique.
Maybe an example where rightmost not unique after shrinking left: Need a case where after shrinking left, the rightmost element appears elsewhere inside the window. For rightmost to be non-unique, there must be another occurrence of the same value somewhere in the window before the rightmost. That other occurrence would be to the left. So the window would contain at least two of that value. But note that the rightmost element is at position r, and there is another occurrence at some position i < r. Then the window includes that duplicate. Now, if we have shrunk left as much as possible while keeping distinct == k, we have ensured that leftmost is unique. Could the rightmost still be non-unique? Yes, e.g., array: 1,2,3,2, k=3? Let's try k=3: need exactly 3 distinct numbers. The whole array has 1,2,3 distinct 3, but also includes duplicate of 2. The window [1,4] length4. Leftmost=1 unique? 1 appears only once. Rightmost=2 appears also at position3. So rightmost not unique. This window has distinct=3, leftmost unique but rightmost not unique. Is this window minimal by inclusion? No, because we can shrink from right: [1,3] (1,2,3) also has distinct=3 and is smaller. So it's not minimal. The minimal length would be [1,3] length3, which has both unique. Our algorithm when processing right=4 (R=4) should find the candidate after shrinking left to make left unique, but we don't shrink right, so it may record [1,4]? Let's simulate:
Array: [1,2,3,2] indices 1..4, k=3.
R=1:1 distinct1.
R=2:2 distinct2.
R=3:3 distinct3 -> after adding, distinct=3. shrink left: left=1, a1=1 freq1=1 -> no shrink. record [1,3] length3, best_len=3.
R=4:2 -> distinct=3? Actually after adding 2 (value2) freq2 becomes2, distinct remains 3. Now while distinct > k? no. shrink left: left=1, a1=1 freq1=1 -> cannot shrink. So we would record [1,4] length4? But we check if distinct == k (yes), then we do shrink left while freq[a[left]]>1. At left=1, freq[1]=1, so no shrink. So we would record [1,4] length4. But we would also check if cur_len < min_len. Since min_len currently is 3 (from earlier), 4 is not less, so we don't update. So we keep best as [1,3], which is correct. So the algorithm only updates when we find a shorter length, so the final best will be the minimal length, which will have both endpoints unique. So even if we sometimes record windows that are not minimal by inclusion (like [1,4] that is not minimal by inclusion), we don't select them if there is a shorter one. So final answer is fine.
But what if the only windows with exactly k distinct numbers are such that none of them have both endpoints unique? Is that possible? That would mean every window with exactly k distinct numbers has at least one endpoint non-unique. Then any such window could be shrunk from that endpoint to produce a strictly smaller window with exactly k distinct numbers, which would be a proper subsegment with exactly k distinct. By repeating, we would eventually get a window that cannot be shrunk further, which would have both endpoints unique. That would be a shorter window with exactly k distinct. So such a minimal window must exist. Hence, if any window exists, there is at least one that is minimal by inclusion (and both endpoints unique). So it's impossible that all windows have a non-unique endpoint without existence of a smaller one; by well-foundedness, there must be a minimal element under inclusion, which will have both endpoints unique. So our algorithm that finds the globally shortest length will definitely find such a window.
Thus, our approach is valid.
Now, complexity O(n) time, O(maxA) space.
We should also think about possible integer overflow? Not.
Edge Cases:
- n = 1, k = 1: array [5]. Then algorithm: R=0: add 5, distinct=1, shrink left? freq[5]=1, no shrink, record len=1, best=(0,0). Output 1 1. Good.
- n = 1, k = 2: impossible, output -1 -1.
Now, confirm with sample2 again: we got best (6,8) length3, but sample output is (2,5). Both correct.
Thus we can implement.
But wait, there is a nuance: The problem says "minimal by inclusion segment [l, r] ... such that there is no segment [x, y] satisfying the property and less then m in length, such that 1 ≤ l ≤ x ≤ y ≤ r ≤ n." They define less in length, but the condition is that there is no segment that is a subsegment of [l, r] (i.e., l ≤ x ≤ y ≤ r) that also satisfies the property and has length smaller than m (the length of [l,r]). Actually, they define: Segment [l, r] ... is called minimal by inclusion, if there is no segment [x, y] satisfying the property and less then m in length, such that 1 ≤ l ≤ x ≤ y ≤ r ≤ n. The phrasing "less then m in length" means the subsegment has length smaller than m (the original length). But since any proper subsegment [x, y] of [l, r] automatically has length ≤ m (strictly less if proper). However, note that if we have a subsegment that is the same length? That can't happen because proper subsegment would have x>l or y<r, so length < m. So the condition is simply: no proper subsegment also has exactly k distinct numbers. So our interpretation is correct.
Now, confirm that a segment of length 1 for k=1 is indeed minimal because there is no proper subsegment. Good.
Now, we need to ensure that our algorithm outputs a segment that satisfies exactly k distinct numbers, and that it is minimal by inclusion. Since we pick a globally shortest segment, it's minimal by inclusion as argued.
Now, think about possible pitfalls with the shrink step: we shrink left while freq[a[left]] > 1. But consider the scenario where left is not the leftmost index of the window? It is. After shrinking, left is updated to a new index. All good.
Now, we must be careful that the shrink step does not cause left to exceed right? In what cases could that happen? If window length is 1, then freq[a[left]] = 1, so while loop condition false. If window length > 1 and all elements are unique, then freq[a[left]] = 1, so condition false. So no issue.
Now, after processing all right, we have best_l and best_r. If best_l == -1, output -1 -1 else output with +1.
Now, test with random arrays to be safe.
But before finalizing, consider if there is any scenario where the shortest window found by the algorithm might not be minimal by inclusion because of some nuance about "exactly k distinct numbers"? The shortest window definitely has both endpoints unique, so it's minimal by inclusion.
Hence solution is correct.
Now, we could also consider an alternative approach: find any segment where leftmost and rightmost are unique. That would also be O(n) maybe. But the shortest segment approach is simpler.
Now, implement.
But I'd like to test on some additional cases:
Case: n=5, k=2, a = [1,1,2,2,2]. Minimal windows with exactly 2 distinct numbers: [2,3] (1,2) length2? positions 2:1,3:2 -> length2. Also [3,4]? (2,2) only 1 distinct. Actually [3,4] has only 2, so not. [1,3] length3, leftmost 1 unique? 1 appears twice? Actually [1,3] includes 1,1,2: leftmost=1 not unique, rightmost=2 appears also later but inside? In [1,3], 2 appears once (only at pos3), so rightmost unique. But leftmost not unique -> can shrink left to [2,3] which is length2 and still has distinct 2. So [1,3] not minimal. So minimal length is 2. Our algorithm should find length2.
Simulate:
R=1:1 distinct1.
R=2:1 distinct1.
R=3:2 distinct2 -> after addition distinct=2, shrink left: left=1, a1=1 freq1=2>1 -> remove, left=2, freq1=1. Check left=2, a2=1 freq1=1 -> no shrink. record [2,3] len2.
R=4:2 distinct2 -> shrink left: left=2, a2=1 freq1=1 -> cannot shrink, record [2,4] len3 (not less).
R=5:2 distinct2 -> shrink left: left=2, a2=1 freq1=1 -> cannot shrink, record [2,5] len4 (not less). So best remains [2,3]. Good.
Case: n=5, k=2, a = [1,2,1,2,1]. Minimal windows: length2 many: [1,2], [2,3]? Actually [2,3] = (2,1) distinct2 length2; [3,4]=(1,2) length2; [4,5]=(2,1) length2. Our algorithm should find length2.
Now, consider if there is a case where the minimal length is not discovered because we never encounter distinct == k? Actually, if there is any window with exactly k distinct, our sliding window algorithm should eventually have distinct == k at some point. Because we extend right, and when we have exactly k distinct, we will capture it. But is it guaranteed that the sliding window with left pointer always maintains a window that contains exactly k when possible? The algorithm ensures that we always have distinct <= k after the while loop that reduces when >k. But if the window never reaches exactly k because we always have < k, then no window exists. But if a window exists, at some right, after adding that element, the distinct count could become >k, then we shrink left to bring it down to <=k. It might become exactly k or less. It could become less if we overshrink? The while loop stops when distinct <= k. It could become < k if we overshrink? Let's examine: Suppose we have distinct > k, we remove leftmost element. This could reduce distinct by 1 if that element's frequency goes to 0. It may also not reduce distinct if that element still appears. We continue removing until distinct <= k. It's possible that we go from >k to exactly k, or we could go below k if we remove a unique element that is not compensated? Actually, if we have distinct > k, the window has at least k+1 distinct. Removing one element could reduce distinct by at most 1. So after removal, distinct could be >= k. But we continue until distinct <= k. Since each removal can reduce distinct by at most 1, we may stop when distinct == k or distinct == k-? Wait, if we have distinct = k+1, after removing one element that is unique, distinct becomes k, we stop (since distinct <= k). If the element removed is not unique, distinct stays k+1, we continue. So we will keep removing until distinct becomes exactly k or perhaps we skip over k? Could we go from >k to < k directly? Suppose we have distinct = k+2. Removing a unique element reduces to k+1, still >k, continue. Next removal of a unique element reduces to k, stop. So we stop at k. So we cannot go below k because we stop when distinct <= k. But what if after a removal, distinct becomes k-1? That would require that we had distinct = k and we removed a unique element that causes distinct to drop to k-1. But we only remove while distinct > k, so we never remove when distinct == k. So we cannot go below k during the while loop. So after the while loop, distinct is either k (if we had >k and brought it down) or remains < k (if we never had >k). So if a window with exactly k exists, at some right after processing, we may have distinct exactly k either immediately after addition (if no >k) or after the while loop reduction from >k to exactly k. So the algorithm will indeed encounter distinct == k for some right. Good.
Now, potential issue: The shrink step (while freq[a[left]] > 1) may move left past the position that would give an even smaller window for a later right? But we don't need to worry because we are evaluating each right independently; the shrink step for current right gives the minimal left for this right. That yields the shortest possible window ending at this right. This is exactly what we need for global minimum.
Now, about memory: We'll allocate freq array of size maybe 100005.
Now, code.
Implementation details:
We'll use 0-indexed positions internally.
Pseudo:
int n, k;
cin >> n >> k;
vector a(n);
for i in [0,n-1]: cin >> a[i];
vector freq(100001, 0); // max a_i = 100000, index from 1
int left = 0, distinct = 0;
int min_len = n+1;
int best_l = -1, best_r = -1;
for (int right = 0; right < n; ++right) {
int val = a[right];
if (freq[val] == 0) distinct++;
freq[val]++;
while (distinct > k) {
int lval = a[left];
freq[lval]--;
if (freq[lval] == 0) distinct--;
left++;
}
if (distinct == k) {
// Shrink left while the leftmost element occurs more than once
while (freq[a[left]] > 1) {
freq[a[left]]--;
left++;
}
int cur_len = right - left + 1;
if (cur_len < min_len) {
min_len = cur_len;
best_l = left;
best_r = right;
}
}
}
if (best_l == -1) cout << "-1 -1\n";
else cout << best_l+1 << " " << best_r+1 << "\n";
Now, test with sample2: we got best_l=5? Actually we got (6,8) in 1-indexed: (6,8). That is length 3. sample output is (2,5) length 4. Both are acceptable. But could there be any scenario where our algorithm outputs a segment that is not minimal by inclusion? Suppose we have a window of minimal length that we found, but after we recorded it, we continue to modify the frequencies and left pointer, which might affect the state for later right; but the recorded segment is stored separately, it's fine.
But we must ensure that the recorded segment indeed has the property of exactly k distinct numbers at the time we recorded it. Yes.
Now, confirm that the segment we output indeed has both endpoints unique at the time of recording? At the moment we recorded, we had just performed the shrink step, so leftmost is unique. But we didn't enforce rightmost uniqueness. However, for a minimal length window, rightmost must be unique. But is it guaranteed that the window we record, which is the shortest overall, automatically has rightmost unique? As argued earlier, if it's globally shortest, both endpoints are unique. So we don't need to explicitly check or enforce rightmost uniqueness. So it's fine.
Thus solution is correct.
Now, think about alternative answer: If there are multiple minimal by inclusion segments, we output any. The shortest segment is one of them.
Now, double-check with a case where there is a tie in length: we output whichever encountered first (if we use <) or we could output any. That's fine.
Now, let's test with a custom case: n=6, k=3, a = [1,2,3,1,2,3]. Minimal length =3. Our algorithm:
R=1:1 distinct1
R=2:2 distinct2
R=3:3 distinct3 -> shrink left: left=1, freq1=1 cannot shrink. record [1,3] len3.
R=4:1 -> distinct3 -> shrink left: left=1, freq1=2>1 -> remove, left=2, freq1=1. check left=2, a2=2 freq2=1 -> record [2,4] len3 (positions 2,3,4? Actually right=4, left=2 => window indices 2-4: 2,3,1 len3) record length3 equal to min_len, maybe not update if < . So final best could be (1,3) or (2,4) depending on if we update on equal. Both valid.
Now, we might also record [3,5], [4,6] etc.
Now, ensure that we handle large values: use array size maybe 100005 or 200005? Actually a_i up to 100000, we need index up to 100000 inclusive. So freq size = 100001 (since 0..100000). But if we use vector freq(100001) that's fine.
Alternatively, we could use unordered_map to be safe if values were larger, but not needed.
Now, confirm time: O(n) and memory O(maxA).
Potential improvements: Since n and a_i up to 1e5, this is efficient.
Now, test with k > number of distinct: algorithm never gets distinct == k, best_l stays -1, output -1 -1.
Now, test with k = number of distinct but some windows: already covered.
Now, consider edge when k = 0? Not possible.
Now, answer.
But wait, we must ensure that the shrink step (while freq[a[left]] > 1) does not invalidate the invariant that the window has exactly k distinct numbers. It doesn't because we only remove elements that have freq >1, so distinct unchanged.
Now, some implementations of sliding window for exactly k distinct may also include a step to shrink right? But we don't need.
Now, final answer.
But let's test on a more tricky case: when k=2, array: [1,2,1,1,2,2]. The minimal length window with exactly 2 distinct numbers? There are windows of length 2: e.g., [1,2] (1,2), [2,3] (2,1), [4,5] (1,2) etc. So min_len=2. Our algorithm should find it.
Simulate:
R=1:1 dist1
R=2:2 dist2 -> shrink? left=1 freq1=1 -> record [1,2] len2.
R=3:1 dist2 -> shrink: left=1 freq1=2>1 -> remove, left=2, freq1=1; left=2 a2=2 freq2=1 -> record [2,3] len2.
R=4:1 dist2 -> shrink: left=2 a2=2 freq2=1 -> cannot shrink, record [2,4] len3 (not less)
R=5:2 dist2 -> shrink: left=2 a2=2 freq2=1? Actually before shrink, after adding a[5]=2, freq2 becomes 2? Let's track frequencies: After R=4 we had left=2, window [2,4] values: pos2=2, pos3=1, pos4=1 => freq2=1, freq1=2. After adding R=5=2, freq2=2, freq1=2, distinct=2. Now shrink: left=2, a2=2 freq2=2>1 -> remove, left=3, freq2=1. Now left=3, a3=1 freq1=2>1 -> remove, left=4, freq1=1. Now left=4, a4=1 freq1=1 -> stop. So window [4,5] length2. Record len2 equal to min_len. So fine.
Now, test with k=2, array: [1,1,1,2,1,1,1]. Minimal length window with exactly 2 distinct? It might be [3,4] (1,2) length2? Actually positions: 3=1,4=2 -> length2, both unique? leftmost=1 appears elsewhere? In window [3,4], 1 appears only once? But there are many 1's outside, but inside only one. So leftmost unique? Yes. Rightmost=2 unique. So length2 exists. Our algorithm should find it.
Simulate:
R=1:1 dist1
R=2:1 dist1
R=3:1 dist1
R=4:2 dist2 -> after addition distinct=2. shrink left: left=1 a1=1 freq1=3>1 -> remove, left=2 freq1=2; still >1? while condition: left=2 a2=1 freq1=2>1 -> remove, left=3 freq1=1; now left=3 a3=1 freq1=1 -> stop. window [3,4] length2. Record. Good.
Now, test with k=2, array: [1,2,2,2]. Minimal length 2: [1,2] length2. Our algorithm: R=2 -> record [1,2] length2. Good.
Now, test with k=2, array: [2,2,2,1]. Minimal length 2: [3,4]? Actually positions: 3=2,4=1 length2? But [3,4] = 2,1 distinct2 length2. Also [1,4]? length4. Our algorithm should find length2. R=4: add 1, after shrink left could yield [3,4]. Let's simulate: R=1:2 dist1; R=2:2 dist1; R=3:2 dist1; R=4:1 dist2 -> shrink left: left=1 a1=2 freq2=3>1 -> remove, left=2 freq2=2; still >1 remove left=2? Actually while loop: after removal left=2, check a[2]=2 freq2=2>1 -> remove, left=3 freq2=1; now left=3 a3=2 freq2=1 -> stop. window [3,4] length2. Good.
Now, test with k=2, array: [1,2,3,2,1]. Minimal length? Possibly [2,3] (2,3) length2, [3,4] (3,2) length2, [4,5] (2,1) length2. Our algorithm: R=2 gives [1,2]? Actually R=2: distinct=2, shrink left? left=1 a1=1 freq1=1 -> record [1,2] length2. That's also valid (1,2) distinct2. So min_len=2. That's fine.
Now, check if there is any case where the minimal length window discovered by the algorithm may have length > some other window that the algorithm never recorded because we didn't shrink right? But the algorithm records for each right the minimal left, giving the shortest window ending at that right. The global minimum over all right is the shortest window overall. So if there exists a window [l,r] of length L, then when we process right = r, at that point after processing, the algorithm will eventually (maybe after shrinking left) produce a window that ends at r and has length <= L (since it minimizes left for that right). Since [l,r] is a window with exactly k distinct, the minimal left for this right will be >= l, so the length found will be <= original length. In fact, it will be the minimal possible length for that ending r. So if there is any window of length L_min overall, then at the right endpoint of that window, the algorithm will find a window of length L_min (or possibly even shorter, but L_min is minimal overall, so it must equal L_min). So we will capture it. So no window is missed.
Now, we must also consider that after we process right = r, we might have already moved left beyond the l of some window due to previous steps. But the algorithm for right = r will still adjust left appropriately (since we may increase left in the while distinct > k or shrink steps). However, it's possible that the window [l,r] is such that before reaching r, left has been moved beyond l, and when we process r, the left pointer is already > l, so we may not be able to obtain a window that ends at r with left = l because we removed some elements that are needed? But we only remove elements when they are not needed to maintain the property. If [l,r] is a valid window, then at the moment we process r, the current window (which may start at some L' > l) might have distinct count maybe less than k or equal? Let's think: The algorithm always maintains a window that starts at some L (current left). As we increase r, we may have moved L forward due to previous steps. Could it be that when we get to r, L is > l, and we cannot move L backwards to l because we have lost frequency information for elements before L? But the algorithm doesn't store earlier elements. However, the minimal left for this r is the maximum index such that [left, r] has exactly k distinct. That left may be > l if l is not maximal left for that r. So the window [l, r] might not be the minimal left for that r; the minimal left for r could be a larger index, resulting in a shorter window. So that's fine because we are looking for the shortest overall. So if [l,r] is of minimal length overall, then l must be the maximal left for that r; otherwise there would be a shorter window ending at r with larger left. So the algorithm will find that left (which is >= l). Actually, if [l,r] is of minimal overall length, then for that r, the maximal left is exactly l? Not necessarily: Suppose there is a window [l,r] of length L that is globally minimal. For that r, the maximal left (the largest left that still yields exactly k distinct) could be some L' >= l. Then the window [L', r] would have length <= L. Since L is globally minimal, length of [L', r] cannot be less than L, so must equal L, implying L' = l. So l is the maximal left. So the algorithm will find left = l for that r. So it's okay.
Now, confirm that the algorithm's state when reaching r will allow left to be moved to l. Since we maintain frequencies only for the current window, we might have removed some elements that are before the current left. But if l is larger than the current left before processing r, then we can move left forward (increase) to reach l. That is possible because we can increase left (by removing elements) as needed. The algorithm does that via the while loops. If l is smaller than the current left, we cannot move left backward because we don't have those elements anymore. But if l is smaller, then the current left > l, meaning that before processing r we have already advanced left beyond l. Could that happen even though [l,r] is a valid window? Possibly if earlier steps forced us to move left forward because we had too many distinct numbers. But if the current left > l, then the window [current left, r-1] may have had some property. At step r, we will add a[r]. The current left might be > l, but that means that the subwindow [current left, r-1] had at most k distinct (maybe exactly k or less). Could we still get back to l? We cannot because we lost information about elements before current left. But do we need to? As argued, if the minimal length window is [l,r], then l must be the maximal left for that r, and the algorithm's current left will be <= that maximal left? Not necessarily. Let's consider a scenario:
Suppose array: [1,2,3,2,1], k=2. The minimal length windows: many length2: [1,2] (1,2), [2,3] (2,3), [3,4] (3,2), [4,5] (2,1). Consider the window [1,2] length2. At r=2, we will process and record it. Now consider a longer window, say [1,5] length5 (distinct 3? Actually distinct 3? 1,2,3,2,1 has distinct 3, so not k=2). So not relevant.
But suppose there is a case where the minimal length window is, say, [3,5] length3? Actually with k=2, minimal length should be 2, so that's not minimal overall.
Now, create a scenario where there is a unique minimal length window at a later part, and earlier we moved left too far due to some condition, but when we get to that r, current left may be less than or equal to l? Actually, current left is always the left boundary of the window we are maintaining. It can only increase. So when we reach r, current left is some value L_cur <= current right (r). Could it be that L_cur > l, where l is the left of the minimal window? Possibly if before reaching r, we encountered elements that forced us to move left forward beyond l. But then at r, the window [L_cur, r] might have distinct count <= k. To have a minimal window [l,r] with l < L_cur, that would mean that there is a window starting earlier that also has exactly k distinct. But if L_cur > l, then [l, r] is a valid window but [L_cur, r] is a subwindow. If [l,r] has exactly k distinct, and [L_cur, r] also has exactly k distinct (maybe if L_cur is after l but still contains k distinct), then [l,r] is not minimal because it contains a proper subsegment with the property. So [l,r] would not be minimal by inclusion, and also not the shortest length because [L_cur, r] is shorter. So the globally shortest window would be at most length of [L_cur, r]. So we don't need to consider [l,r] if it's not minimal. Therefore, if the current left has advanced beyond l, it means that l is not the maximal left for that r, and there exists a shorter window ending at r (starting at L_cur). So the shortest window for that r would be found by shrinking left further (which we do). So it's fine.
Thus the algorithm is correct.
Now, let's think about one more nuance: Could there be a case where the globally shortest window has length L, but the algorithm never records it because at that right, after shrinking left, we get a window of length L, but then we later, due to some operation, modify the frequencies such that when we later check for that same right? No, we record at that moment.
Now, we should also verify the correctness for k = 0? Not needed.
Now, I think it's good.
Now, I'll also consider alternative simpler solution: find any segment with exactly k distinct where both ends are unique. That could be done by iterating over the array and using two pointers but maybe more complex. Our method is fine.
Now, let's produce final answer.
But note: The problem statement says "Print a space-separated pair of integers l and r (1 ≤ l ≤ r ≤ n) such, that the segment [l, r] is the answer to the problem. If the sought segment does not exist, print "-1 -1" without the quotes. If there are multiple correct answers, print any of them." So we can output the minimal length segment.
Now, confirm that the sample output #2 can be (2,5) or (6,8) etc. The problem's output (2,5) is 4 length. Our algorithm might output (6,8) length3. That's acceptable per problem, because they said any correct answer. So it's fine.
Now, I should also consider the possibility that the algorithm might output a segment that is not minimal by inclusion if min_len is not the absolute minimum? But we are tracking minimum length, so the final best is of minimum length. So it's minimal by inclusion.
Now, maybe there is a scenario where the minimal length segment does not exist because there is a segment with exactly k distinct numbers but all such segments have length at least something, but the minimal length segment might not be minimal by inclusion? That's impossible as argued.
Thus final.
Now, I'll code.
Implementation details in C++:
#include
#include
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, k;
cin >> n >> k;
vector<int> a(n);
for (int i = 0; i < n; ++i) cin >> a[i];
const int MAX_A = 100000;
vector<int> freq(MAX_A + 1, 0);
int left = 0, distinct = 0;
int min_len = n + 1;
int best_l = -1, best_r = -1;
for (int right = 0; right < n; ++right) {
int val = a[right];
if (freq[val] == 0) distinct++;
freq[val]++;
// If we exceed k distinct, move left to reduce
while (distinct > k) {
int lval = a[left];
freq[lval]--;
if (freq[lval] == 0) distinct--;
left++;
}
// If we have exactly k distinct, try to minimize window from left
if (distinct == k) {
// Shrink from left while leftmost element is not unique within the window
while (freq[a[left]] > 1) {
freq[a[left]]--;
left++;
}
int cur_len = right - left + 1;
if (cur_len < min_len) {
min_len = cur_len;
best_l = left;
best_r = right;
}
}
}
if (best_l == -1) {
cout << "-1 -1\n";
} else {
cout << best_l + 1 << " " << best_r + 1 << "\n";
}
return 0;
}
Now, test with given samples:
Sample1:
Input:
4 2
1 2 2 3
Our program: best_l=0, best_r=1 (1-indexed (1,2)) -> prints "1 2". Correct.
Sample2:
Input:
8 3
1 1 2 2 3 3 4 5
Our program may output "6 8" (1-indexed) if it updates on < only, not <=. That is acceptable. But to match the sample output exactly we could modify to output any, but it's fine. In an online judge, they likely accept any correct answer.
Sample3:
7 4
4 7 7 4 7 4 7
No window with 4 distinct, output "-1 -1". Correct.
Now, test with a case where k=1, n=5, a = [2,2,2,2,2]. Our algorithm: min_len will be 1 (first at R=0 record len1, best=(0,0)). Output "1 1". That's minimal by inclusion? Yes, single element is minimal. Also note that there are segments of length >1 with exactly 1 distinct number, but they are not minimal because they contain a single element segment with 1 distinct number. So output "1 1" is fine.
Now, test with k=2, n=2, a=[1,2] => algorithm records [0,1] len2 -> output "1 2". That's minimal.
Now, test with k=2, n=2, a=[1,1] => no window with 2 distinct. Output -1 -1.
Now, test with k=100000, n=100000 all distinct. Then algorithm will eventually when right = k-1? Actually k = n, all distinct. The minimal length window with exactly n distinct is the whole array length n. Our algorithm will record at right = n-1 (last index) after shrinking left cannot shrink (since all unique). So min_len = n, output "1 n". Correct.
Now, test with large values.
Thus solution is ready.
Now, note: The frequency array size is 100001, but we might also need to consider if a_i can be up to 10^5 exactly, index 100000. So vector freq(100001) works.
Now, could we improve by using map for smaller memory if a_i larger? But fine.
Now, let's think about any pitfalls: The while (freq[a[left]] > 1) might access a[left] when left > right? That would only happen if window length is 0? But distinct == k ensures there is at least one element? Actually if distinct == k, the window contains at least k elements, so left <= right. So fine.
Now, we might also consider the scenario where k > n. Then it's impossible, algorithm will never have distinct == k (since max distinct <= n). best_l stays -1, output -1 -1. Good.
Now, final answer.
But wait, the problem states "If the sought segment does not exist, print "-1 -1"." So that's covered.
Now, discuss time complexity: O(n) because each element added once, and left moves at most n times across the loop.
Now, I'll produce final explanation.
However, let's double-check the definition: "Segment [l, r] (1 ≤ l ≤ r ≤ n) of length m = r - l + 1, satisfying the given property, is called minimal by inclusion, if there is no segment [x, y] satisfying the property and less then m in length, such that 1 ≤ l ≤ x ≤ y ≤ r ≤ n." This means that there is no subsegment (with the property) that is strictly inside [l, r] (i.e., l ≤ x ≤ y ≤ r) and has length smaller than m. But note that if a subsegment has the same length, it would have to be equal to [l, r] because l ≤ x and y ≤ r and length equal implies x=l and y=r. So that's fine.
Thus condition is exactly no proper subsegment with exactly k distinct numbers.
Now, is it possible that a segment has both endpoints unique but there exists a proper subsegment (not obtained by shrinking just one side) that also has exactly k distinct numbers? For example, suppose we have segment [l, r] with both endpoints unique, but there is some interior subsegment [x, y] with l < x ≤ y < r that also has exactly k distinct numbers. Could that happen? Let's think. Since [l, r] has exactly k distinct numbers and both endpoints are unique, the distinct set is exactly those k values. Removing l removes one distinct value, so the distinct count becomes k-1. Similarly, removing r reduces to k-1. But what about removing both l and r? That yields [l+1, r-1] with distinct count possibly k-2 or maybe still k? Could it be k? If the values at l and r are the only occurrences of two distinct values, then removing both would remove those two values, so distinct count becomes at most k-2. So [l+1, r-1] has < k. Could there be a subsegment that removes l but not r, but also removes some other duplicates to bring back a distinct value? Wait, the only way to have exactly k distinct numbers in a subsegment that does not include l or r is if the subsegment still contains all k distinct values. But if the subsegment does not include l, then it lacks the value at l. To have all k distinct, it must contain that value elsewhere. However, we assumed that value at l is unique in the whole segment. So it cannot appear elsewhere. Therefore any subsegment that excludes l will miss that value, so distinct count ≤ k-1. Similarly, any subsegment that excludes r will miss that value. Hence any proper subsegment, which either excludes l or excludes r (or both), will miss at least one of those unique values, so distinct count < k. Therefore no proper subsegment can have exactly k distinct numbers. So condition of both endpoints being unique is indeed sufficient for minimal by inclusion. Good.
Thus our algorithm yields such a segment.
Now, finalize.
Potential alternative: Use binary search on length, but O(n log n). Not needed.
Thus solution is ready.
Now, I'll provide explanation in final answer.
Let's produce final answer with code and explanation. We need to find any segment ([l, r]) that contains exactly (k) distinct numbers and is minimal by inclusion, i.e., no proper subsegment also has exactly (k) distinct numbers.
A segment is minimal by inclusion exactly when both its leftmost and rightmost elements occur only once inside the segment (for (k>1); for (k=1) any single element works).
Such segments are precisely the shortest segments among all that contain exactly (k) distinct numbers – a shortest segment cannot have a non‑unique endpoint, otherwise we could shrink it and still have (k) distinct numbers, contradicting minimal length.
Therefore we can simply find a shortest subarray with exactly (k) distinct numbers.
We use a sliding window with two pointers left and right.
- Maintain a frequency array of the current window.
- Expand
right one step, update frequencies and the number dist of distinct values.
- While
dist > k, move left forward to reduce the window.
- When
dist == k, shrink the window from the left as long as the leftmost element appears more than once (this does not change dist).
Now the window is the shortest possible ending at this right that still has exactly (k) distinct numbers.
- Record its length if it improves the global minimum.
After processing all positions, output the recorded segment (converted to 1‑based indices) or -1 -1 if none exists.
The algorithm runs in (O(n)) time and uses (O(\max a_i)) memory (or (O(n)) with a hash map).
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
cin >> n >> k;
vector<int> a(n);
for (int i = 0; i < n; ++i) cin >> a[i];
const int MAX_A = 100000;
vector<int> freq(MAX_A + 1, 0);
int left = 0, dist = 0;
int best_len = n + 1, best_l = -1, best_r = -1;
for (int right = 0; right < n; ++right) {
int val = a[right];
if (freq[val] == 0) ++dist;
++freq[val];
// too many distinct values -> shrink from left
while (dist > k) {
int lval = a[left];
--freq[lval];
if (freq[lval] == 0) --dist;
++left;
}
// exactly k distinct -> make left as large as possible
if (dist == k) {
while (freq[a[left]] > 1) {
--freq[a[left]];
++left;
}
int cur_len = right - left + 1;
if (cur_len < best_len) {
best_len = cur_len;
best_l = left;
best_r = right;
}
}
}
if (best_l == -1)
cout << "-1 -1\n";
else
cout << best_l + 1 << " " << best_r + 1 << "\n";
return 0;
}