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] + " ");
}
}
}
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With