Home > Blockchain >  Removing only one element of the duplicate elements using collections in java
Removing only one element of the duplicate elements using collections in java

Time:12-05

I have to find all the duplicates and return them using collections. For example, if list = {1,1,2,2,2} it will return {1,2,2}. So in other words, the pattern is you return -1 of the number of duplicates.

Here is the method:

public static Integer[] returnDuplicate (Integer[] list ){
        // Insert your code here. You may want to change the return value. 
    
        return null 
}

public static Integer[] returnDuplicate (Integer[] list ){
        List<Integer> uniqueList = new ArrayList<Integer>();
        for (int k = 0; k < list.length; k  ) {
                  for (int j = 0; j < list.length; j  ) {
                       if (list[k] == list[j] && k != j && !uniqueList.contains(list[k])) {
                uniqueList.add(list[k]);
            }
                   }
        }
        Integer[] result = new Integer[uniqueList.size()];
        int i = 0;
        for (Integer val : uniqueList) {
            result[i  ] = val;
        }
        return result;
        
}

This is my code but it's returning {1,2} instead of {1,2,2}

CodePudding user response:

Since you're allowed to use Collections, you can maintain a HashSet of elements that have been already encountered (it would be more performant than maintain List because contains() check on a list performs iteration over the whole list under the hood which results in O(n) time complexity, meanwhile HashSet produces the result almost instantly in O(1)).

And while iterating offer you need to offer the next element to the Set, if the element gets rejected, i.e. method Set.add() returns false, would mean that it's a duplicate, and we can add it to the resulting list of duplicated values.

public static Integer[] returnDuplicates(Integer[] list){
    List<Integer> duplicates = new ArrayList<>();
    Set<Integer> seen = new HashSet<>();
    for (Integer next: list) {
        if (!seen.add(next)) duplicates.add(next);
    }
    return duplicates.toArray(Integer[]::new);
}

main()

public static void main(String[] args) {
    System.out.println(Arrays.toString(returnDuplicates(new Integer[]{1, 1, 2, 2, 2})));
}

Output:

[1, 2, 2]

CodePudding user response:

This should do the trick:

 public static List<Integer> returnDuplicate (Integer[] list ){
            List<Integer> uniqueList = new ArrayList<Integer>();
            int prev = -1;
            for(Integer el : list){
              if(el == prev && prev != -1)
                uniqueList.add(el);
              prev = el;
            }
    
            return uniqueList;
            
    }
  • Related