![]() |
VOOZH | about |
Given an array and an integer K. We need to find the maximum of every segment of length K which has no duplicates in that segment.
Examples:
Input : a[] = {1, 2, 2, 3, 3},
K = 3.
Output : 1 3 2
For segment (1, 2, 2), Maximum = 1.
For segment (2, 2, 3), Maximum = 3.
For segment (2, 3, 3), Maximum = 2.
Input : a[] = {3, 3, 3, 4, 4, 2},
K = 4.
Output : 4 Nothing 3
A simple solution is to run two loops. For every subarray, find all distinct elements and print maximum unique elements.
An efficient solution is to use the sliding window technique. We have two structures in every window.
We process the first K-1 elements and store their counts in the hash table. We also store unique elements in set. Now we, one by one, process the last element of every window. If the current element is unique, we add it to the set. We also increase its count. After processing the last element, we print the maximum from the set. Before starting the next iteration, we remove the first element of the previous window.
Implementation:
1 3 2
Time Complexity: O(N Log K)
Auxiliary Space: O(N)