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] + " ");
}
}
}
Keeping one extra variable for maintaining count, plus sorting of array in the initial phase.
output
Agreed to Tim @tim-biegeleisen. Just minor change. Use the Arrays to sort the array.
public class DuplicateClass {
}
This is the simplest solution I can think of. I just added an extra counter so that integers with two or more repetitions still in the array are ignored.
My test run: Test run
Input: 1, 2, 3, 4, 2, 4, 1, 1, 1
Duplicates: 2 4 1
Number of duplicates: 3
These are all great answers. One other is to use an int/double and set it's bits when you encounter a number. This works if the array's values are less than 32/64 depending on the type you use.
Below is an example of how you would do that with an integer.
I believe the the other answers are better given your question..but demonstrating this as an alternative shows that you're thinking about it dynamically. If the requirements of the question changed a little this answer might be more appropriate.
Further if you only need to keep track of duplicates given the smallest footprint possible, you could do something similar to what is above or use java's BitSet class to make your life easier.
http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html
Edit: It is also possible to have values higher than 64 given that you create a function that holds an array of bytes like the BitSet class. For this exact question this isn't helpful given the constraint to not use an array or collection.
Output:
There is one method where you can use Math.abs. You should check for the sign positive.If it is positive then make it negative. If negative then that's the duplicated number or the repeated number. Example: A[] = {1, 1, 2, 3, 2} i=0; Check sign of A[abs(A[0])] which is A[1]. A[1] is positive, so make it negative. Array now becomes {1, -1, 2, 3, 2}
i=1; Check sign of A[abs(A[1])] which is A[1]. A[1] is negative, so A[1] is a repetition. Then just put all those repeated numbers into a list and print the size of the list.
The code in python is
Solution 2: Taking 2 pointers
Solution 3: HashSet
Solution:4(same concept as solution 1 but code is in Java)