Q4 PepCoding | Count Distinct Elements In Every Window Of Size K
Mon Jan 23 2023 07:57:31 GMT+0000 (Coordinated Universal Time)
Saved by
@Ayush_dabas07
import java.util.*;
public class Main {
public static ArrayList<Integer> solution(int[] arr, int k) {
ArrayList<Integer> res = new ArrayList<>();
HashMap<Integer,Integer> map = new HashMap<>();
int j = 0 ;
//adding first k elements in the hashmap
while(j<k){
int of = map.getOrDefault(arr[j],0);
map.put(arr[j],of+1);
j++;
}
res.add(map.size());
//moving the window of K at one unit
for(int i =0 ; j < arr.length ; j++,i++){
int last = arr[i];
//removing last element frequency of the window
int of = map.get(arr[i]);
of--;
if(of == 0){
map.remove(last);
}
else{
map.put(last , of);
}
//adding next element of the window
map.put(arr[j] , map.getOrDefault(arr[j],0)+1);
res.add(map.size());
}
return res;
}
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int[] arr = new int[scn.nextInt()];
for (int i = 0; i < arr.length; i++) {
arr[i] = scn.nextInt();
}
int k = scn.nextInt();
ArrayList<Integer> ans = solution(arr,k);
for(int a : ans){
System.out.print(a + " ");
}
}
}
content_copyCOPY
https://www.pepcoding.com/resources/data-structures-and-algorithms-in-java-levelup/hashmap-and-heaps/count-distinct-elements-in-every-window-of-size-k-official/ojquestion
Comments