Tutorialspoint.dev

Maximum Unique Element in every subarray of size K

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 element.

An efficient solution is to use sliding window technique. We maintain two structures in every window.
1) A hash table to store counts of all elements in current window.
2) A self balancing BST (implemented using set in C++ STL and TreeSet in Java). The idea is to quickly find maximum element and update maximum element.

We process first K-1 elements and store their counts in hash table. We also store unique elements in set. Now we one by one process last element of every window. If current element is unique, we add it to set. We also increase its count. After processing last element, we print maximum from set. Before starting next iteration, we remove first element of previous window.

C++

// C++ code to calculate maximum unique
// element of every segment of array
#include <bits/stdc++.h>
using namespace std;
  
void find_max(int A[], int N, int K)
{
    // Storing counts of first K-1 elements
    // Also storing distinct elements.
    map<int, int> Count;
    for (int i = 0; i < K - 1; i++)
        Count[A[i]]++;
    set<int> Myset;
    for (auto x : Count)
        if (x.second == 1)
            Myset.insert(x.first);
  
    // Before every iteration of this loop,
    // we maintain that K-1 elements of current
    // window are processed.
    for (int i = K - 1; i < N; i++) {
  
        // Process K-th element of current window
        Count[A[i]]++;
        if (Count[A[i]] == 1)
            Myset.insert(A[i]);
        else
            Myset.erase(A[i]);
  
        // If there are no distinct
        // elements in current window
        if (Myset.size() == 0) 
            printf("Nothing ");
          
        // Set is ordered and last element
        // of set gives us maximum element.
        else 
            printf("%d ", *Myset.rbegin());
          
        // Remove first element of current 
        // window before next iteration.
        int x = A[i - K + 1];
        Count[x]--;
        if (Count[x] == 1)
            Myset.insert(x);
        if (Count[x] == 0)
            Myset.erase(x);
    }
}
  
// Driver code
int main()
{
    int a[] = { 1, 2, 2, 3, 3 };
    int n = sizeof(a) / sizeof(a[0]);
    int k = 3;
    find_max(a, n, k);
    return 0;
}

Python3

# Python3 code to calculate maximum unique
# element of every segment of array
def find_max(A, N, K):

# Storing counts of first K-1 elements
# Also storing distinct elements.
Count = dict()
for i in range(K – 1):
Count[A[i]] = Count.get(A[i], 0) + 1

Myset = dict()
for x in Count:
if (Count[x] == 1):
Myset[x] = 1

# Before every iteration of this loop,
# we maintain that K-1 elements of current
# window are processed.
for i in range(K – 1, N):

# Process K-th element of current window
Count[A[i]] = Count.get(A[i], 0) + 1

if (Count[A[i]] == 1):
Myset[A[i]] = 1
else:
del Myset[A[i]]

# If there are no distinct
# elements in current window
if (len(Myset) == 0):
print(“Nothing”)

# Set is ordered and last element
# of set gives us maximum element.
else:
maxm = -10**9
for i in Myset:
maxm = max(i, maxm)
print(maxm)

# Remove first element of current
# window before next iteration.
x = A[i – K + 1]
if x in Count.keys():
Count[x] -= 1
if (Count[x] == 1):
Myset[x] = 1
if (Count[x] == 0):
del Myset[x]

# Driver code
a = [1, 2, 2, 3, 3 ]
n = len(a)
k = 3
find_max(a, n, k)

# This code is contributed
# by mohit kumar


Output:

1
3
2

Time Complexity : O(N Log K)



This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter