Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java + Count duplicates from int array without using any Collection or another intermediate Array

As a part of the Java interview question paper I have got following issue to solve. But I am bit wonder whether how can I implement it without any Collection or intermediate Array.

Question:- Count duplicates from int array without using any Collection or another intermediate Array

Input values:- {7,2,6,1,4,7,4,5,4,7,7,3, 1}  

Output:- Number of duplicates values: 3
         Duplicates values: 7, 4, 1

I have implemented following solution but was not completed one. Any one has some idea? Thanks.

public static void duplicate(int numbers[]) {

    for (int i = 0; i < numbers.length; i++) {

        boolean duplicate = false;
        int j = 0;

        while (j < i){

            if ((i != j) && numbers[i] == numbers[j]) {
                duplicate = true;
            }

            j++;
        }

        if (duplicate) {
            System.out.print(numbers[i] + " ");
        }
    }
}
like image 458
Channa Avatar asked Jul 31 '15 05:07

Channa


People also ask

How do you remove duplicates from an array in Java without using collections?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.


1 Answers

 private static int solution3(List<Integer> inputArr) {
    // Time Complexity O(N)
    // Space Complexity O(1)
    // Stream
    return (int) inputArr.stream()
            .collect(Collectors
                    .toMap(Function.identity(), v -> 1, Integer::sum))
            .entrySet().stream()
            .filter(k -> k.getValue() >= 2)
            .count();
}
like image 118
Azamat Toshtemirov Avatar answered Oct 04 '22 13:10

Azamat Toshtemirov