HackerRank Java- Dequeue




In this problem, you are given N integers. You need to find the maximum number of unique integers among all the possible contiguous subarrays of size M.

Note: Time limit is 3 second for this problem.



  1. import java.util.*;
  2. public class test {
  3. public static void main(String[] args) {
  4. Scanner in = new Scanner(System.in);
  5. Deque deque = new ArrayDeque<>();
  6. HashSet<Integer> set = new HashSet<>();
  7. int n = in.nextInt();
  8. int m = in.nextInt();
  9. int max = Integer.MIN_VALUE;
  10. for (int i = 0; i < n; i++) {
  11. int input = in.nextInt();
  12. deque.add(input);
  13. set.add(input);
  14. if (deque.size() == m) {
  15. if (set.size() > max)
  16. max = set.size();
  17. int first = (int) deque.remove();
  18. if (!deque.contains(first))
  19. set.remove(first);
  20. }
  21. }
  22. System.out.println(max);
  23. }
  24. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube