VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-unique-element-every-subarray-size-k/

⇱ Maximum Unique Element in every subarray of size K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum Unique Element in every subarray of size K

Last Updated : 1 Dec, 2022

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.

  1. A hash table to store counts of all elements in the current window. 
  2. A self-balancing BST (implemented using set in C++ STL and TreeSet in Java). The idea is to quickly find the maximum element and update the maximum elements.

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:


Output
1
3
2

Time Complexity: O(N Log K)
Auxiliary Space: O(N)

Comment