//Given an array of integers and a number k . Find the count of distinct elements in every window of size k in the array .

import java.util.*;
import java.lang.*;
import java.io.*;

// The main method must be in a class named "Main".
class Main {
    
    // Function to count distinct elements in every window of size k
    public static int[] countDistinctInWindows(int[] arr, int k) {
        int n = arr.length;
        int numberofsubarray = n-k+1 ;
        int [] ans = new int[numberofsubarray];

        for(int i=0 ; i<numberofsubarray ; i++){
            HashSet<Integer> temp = new HashSet<>();
            for(int j=i ; j<i+k ; j++){
                temp.add(arr[j]);
            }
            ans[i] = temp.size();
        }
        return ans ; 
    }
    
    

    public static void main(String[] args) {
        int[] arr = {2, 4, 3, 8, 3, 9, 4, 9};
        int k = 4;

        int[] result = countDistinctInWindows(arr, k);

        System.out.println("Count of distinct elements in windows: " + Arrays.toString(result));
    }
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: