HackerRank Java Dequeue problem solution YASH PAL, 31 July 2024 In this HackerRank Java Dequeue problem in the java programming language, you are given N integers. You need to find the maximum number of unique integers among all the possible contiguous subarrays of size M. HackerRank Java Dequeue problem solution. import java.util.*; public class test { public static void main(String[] args) { Scanner in = new Scanner(System.in); final Deque<Integer> deque = new ArrayDeque<Integer>(); final Map<Integer, Integer> map = new HashMap<Integer, Integer>(); final int n = in.nextInt(); final int m = in.nextInt(); int res = 0; for (int i = 0; i < n; i++) { final int num = in.nextInt(); deque.addLast(num); if (map.containsKey(num)) { map.put(num, map.get(num).intValue() + 1); } else { map.put(num, 1); } if (deque.size() == m + 1) { final int key = deque.removeFirst(); final int v = map.get(key); if (v == 1) { map.remove(key); } else { map.put(key, v - 1); } } final int cnt = map.size(); if (cnt > res) { res = cnt; } } System.out.println(res); } } Second solution import java.util.*; public class test { public static void main(String[] args) { Scanner in = new Scanner(System.in); Deque<Integer> deque = new ArrayDeque<Integer>(); HashMap<Integer, Integer> freqs = new HashMap<Integer, Integer>(); int n = in.nextInt(); int m = in.nextInt(); int ans = 0, countDistinct = 0; for (int i = 0; i < n; i++) { int num = in.nextInt(); deque.addLast(num); if (freqs.get(num) == null) freqs.put(num,0); freqs.put(num,freqs.get(num)+1); if (freqs.get(num)==1) countDistinct++; if (deque.size()==m+1){ int rem = deque.removeFirst(); freqs.put(rem,freqs.get(rem)-1); if (freqs.get(rem) == 0) countDistinct--; } if (deque.size()==m){ if (countDistinct > ans) ans = countDistinct; } } System.out.println(ans); } } A solution in java8 programming. import java.util.*; public class test { public static void main(String[] args) { Scanner in = new Scanner(System.in); Deque<Integer> deque = new ArrayDeque<>(); HashSet<Integer> set = new HashSet<>(); int n = in.nextInt(); int m = in.nextInt(); int max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { int input = in.nextInt(); deque.add(input); set.add(input); if (deque.size() == m) { if (set.size() > max) max = set.size(); int first = deque.remove(); if (!deque.contains(first)) set.remove(first); } } System.out.println(max); } } coding problems hackerrank solutions java