Narasimha
Narasimha

Reputation: 21

How to find duplicate elements in array in effective way? I mean to say with very less iterations

How to find the duplicate element in an array which is having lacks of elements? If I iterate the array for lacks of times the performance will became slow. What is the best way to iterate an array in efficient way? Or else can we use any other Java collection object to find the duplicates with less number of iterations or less time complexity?

Upvotes: 0

Views: 1752

Answers (2)

user14838237
user14838237

Reputation:

It depends on the task conditions, the first approach is faster, and the last one is slower:

Character[] chars = {'A', 'A', 'B', 'B', 'B', 'C'};
  1. If you want to filter certain elements and get count of them:

    Long countB = Arrays.stream(chars)
            .filter(ch -> ch.equals('B')).count();
    
    System.out.println(countB); // 3
    
  2. If you want to get an array of distinct elements:

    Character[] distinct = Arrays.stream(chars)
            .distinct().toArray(Character[]::new);
    
    System.out.println(Arrays.toString(distinct)); // [A, B, C]
    

    Or you can use HashSet:

    HashSet<Character> set = new HashSet<>(Arrays.asList(chars));
    
    System.out.println(set); // [A, B, C]
    
  3. If you want to collect a map of duplicates:

    Map<Character, Long> duplicates = Arrays.stream(chars)
            .collect(Collectors.groupingBy(ch -> ch, Collectors.counting()));
    
    System.out.println(duplicates); // {A=2, B=3, C=1}
    

Upvotes: 0

Zach_Mose
Zach_Mose

Reputation: 357

You can use a HashSet because Sets don't allow duplicates, just loop over array of elements and insert them into a HashSet using the add() method. If the add() method returns back false then that element already exists in the set and it is there for your duplicate. This way you only loop over the array once which results in a time and space complexity of O(n).

Upvotes: 1

Related Questions