Skip to main content

Java Dequeue HackerRank Solution with Example

HackerRank Solution for Java Dequeue Problem

HackerRank Solution for Java Dequeue Problem

Problem Description :

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.

Sample 1 :

Input :

6 3
5 3 5 2 3 2

Output :

3

Explanation :

In the sample testcase, there are 4 subarrays of contiguous numbers.

a1 = [5 3 5] - Has unique 2 numbers.
a2 = [3 5 2] - Has unique 3 numbers.
a3 = [5 2 3] - Has unique 3 numbers.
a4 = [2 3 2] - Has unique 2 numbers.

in these subarrays, there are 2, 3, 3, 2 unique numbers, respectively. The maximum amount of unique numbers among all possible contiguous subarrays is 3.

Sample 2 :

Input :

6 3
5 9 8 6 8 7 4 2 3 3

Output :

5

Explanation :

a1 = [5 9 8 6 8] - Has unique 4 numbers.
a2 = [9 8 6 8 7] - Has unique 4 numbers.
a3 = [8 6 8 7 4] - Has unique 4 numbers.
a4 = [6 8 7 4 2] - Has unique 5 numbers.
a5 = [8 7 4 2 3] - Has unique 5 numbers.
a6 = [7 4 2 3 3] - Has unique 4 numbers. 

in these subarrays, there are 4, 4, 4, 5, 5, 4 unique numbers, respectively. The maximum amount of unique numbers among all possible contiguous subarrays is 5.

Before you jump on code, first learn about Queue interface in Java :

import java.util.*;

public class test {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Deque deque = new ArrayDeque<>();
        int n = in.nextInt();
        int m = in.nextInt();
        long maxCount = 0;
        Set<Integer> set = new LinkedHashSet<>();
     
        for (int i = 0; i < n; i++) {
            int num = in.nextInt();
            deque.add(num);
            set.add(num);

            if (deque.size() == m) {
                if (set.size() > maxCount) {
                    maxCount = set.size();
                }
               
                int removed = (int) deque.remove();
               
                if (!deque.contains(removed)) {
                    set.remove(removed);
                }
            }
        }
        System.out.println(maxCount);
    }
}

Code Explanation :

  • Here we have already defined Queue . Now define Set and initialize with LinkedHashSet (we can initialize with HashSet also).
  • We take N as Queue size and M as sub array size.
  • Loop through 0 to N (queue size).
    • Now add user input into both Queue and Set.
    • We perform operation if queue size becomes same as M (Sub array size).
    • In set, only unique elements are stored. so we check size of set and if its size greater than maxCount variable then store set size into maxCount. (As we have to print answer of maximum number of unique integers among all possible contiguous subarrays).
    • Now, remove head element of Queue. (remove() method return head as queue follows FIFO order).
    • Now, remove element from Set that are not duplicate in Queue. Lets take example,
    • Queue = [5, 3, 5], Set = [5, 3]. Now 5 is present 2 times in Queue and 1 time in Set. Now if remove 5 from Queue and Set also then we will get wrong output. Because 5 present 1 times in Set.
  • Print maxCount.

Output Explanation :

Queue = [5, 3, 5, 2, 3, 2], n = 6, m = 3

  • For loop, i = 0
    • deque = [5], set = [5]
  • i = 1
    • deque = [5, 3], set = [5, 3]
  • i = 2
    • deque = [5, 3, 5], set = [5, 3]
    • deque.size() == m | 3 = 3 becomes true
      • set.size() > maxCount | 2 > 0 becomes true
        • maxCount = 2
      •  removed = deque.remove() | removed = 5 
      • !deque.contains(removed) | queue contains 5 | becomes false
  • i = 3, maxCount = 2
    • deque = [3, 5, 2], set = [5, 3, 2]
    • deque.size() == m | 3 = 3 becomes true
      • set.size() > maxCount | 3 > 0 becomes true
        • maxCount = 3
      •  removed = deque.remove() | removed = 3
      • !deque.contains(removed) | queue does contains 3 | becomes true
        • set.remove(3) | set = [5, 2]
  • i = 4, maxCount = 3
    • deque = [5, 2, 3], set = [5, 2, 3]
    • deque.size() == m | 3 = 3 becomes true
      • set.size() > maxCount | 3 > 3 becomes false
      • removed = deque.remove() | removed = 5
      • !deque.contains(removed) | queue does contains 5 | becomes true
        • set.remove(5) | set = [2, 3]
  • i = 5, maxCount = 3
    • deque = [2, 3, 2], set = [2, 3]
    • deque.size() == m | 3 = 3 becomes true
      • set.size() > maxCount | 3 > 2 becomes false
      • removed = deque.remove() | removed = 2
      • !deque.contains(removed) | queue contains 2 | becomes false
  • i = 6 | 6 < 6 becomes false
  • maxCount = 3 

We can also solve this problem without Set, but its give Timeout error in some HackeRank test cases. But as learning purpose we can refer that.

    for (int i = 0; i < n; i++) {
       
        int num = in.nextInt();
        deque.add(num);
       
        if (deque.size() == m) {
           
            long count = deque.stream().distinct().count();
            maxCount = count > maxCount ? count : maxCount;
         
            if (count > maxCount) {
                maxCount = count;
            }
          deque.pollLast();
        }
    }
    System.out.println(maxCount);

Related articles :

 

Comments

Popular posts from this blog

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And last

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st