We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Runtime: O(n) using HashMap and Deque.
Space Complexity: O(n)
publicclasstest{publicstaticvoidmain(String[]args){HashMap<Integer,Integer>map=newHashMap<>();Deque<Integer>deque=newArrayDeque<>();Scannerscan=newScanner(System.in);intn=scan.nextInt();intm=scan.nextInt();intmax=map.size();for(inti=0;i<n;i++){/* Remove old value (if necessary) */if(i>=m){intold=deque.remove();if(map.get(old)==1){map.remove(old);}else{map.put(old,map.get(old)-1);}}/* Add new value */intnum=scan.nextInt();deque.add(num);map.merge(num,1,Integer::sum);max=Math.max(max,map.size());/* If all integers are unique, break out of loop */if(max==m){break;}}scan.close();System.out.println(max);}}
Java Dequeue
You are viewing a single comment's thread. Return to all comments →
Java solution - passes 100% of test cases
From my HackerRank solutions.
Runtime: O(n) using HashMap and Deque.
Space Complexity: O(n)