I have been asked this question in a job interview and I have been wondering about the right answer.
You have an array of numbers from 0 to n-1, one o
public class FindDuplicate {
public static void main(String[] args) {
// assume the array is sorted, otherwise first we have to sort it.
// time efficiency is o(n)
int elementData[] = new int[] { 1, 2, 3, 3, 4, 5, 6, 8, 8 };
int count = 1;
int element1;
int element2;
for (int i = 0; i < elementData.length - 1; i++) {
element1 = elementData[i];
element2 = elementData[count];
count++;
if (element1 == element2) {
System.out.println(element2);
}
}
}
}
As described,
You have an array of numbers from 0 to n-1, one of the numbers is removed, and replaced with a number already in the array which makes a duplicate of that number.
I'm assuming elements in the array are sorted except the duplicate entry. If this is the scenario , we can achieve the goal easily as below :
public static void main(String[] args) {
//int arr[] = { 0, 1, 2, 2, 3 };
int arr[] = { 1, 2, 3, 4, 3, 6 };
int len = arr.length;
int iMax = arr[0];
for (int i = 1; i < len; i++) {
iMax = Math.max(iMax, arr[i]);
if (arr[i] < iMax) {
System.out.println(arr[i]);
break;
}else if(arr[i+1] <= iMax) {
System.out.println(arr[i+1]);
break;
}
}
}
using the sliding window trick to traverse the array O(n)
Space is O(1)
Arrays.sort(input);
for(int i = 0, j = 1; j < input.length ; j++, i++){
if( input[i] == input[j]){
System.out.println(input[i]);
while(j < input.length && input[i] == input[j]) j++;
i = j - 1;
}
}
Test case int[] { 1, 2, 3, 7, 7, 8, 3, 5, 7, 1, 2, 7 }
output 1, 2, 3, 7
One working solution:
asume number are integers
create an array of [0 .. N]
int[] counter = new int[N];
Then iterate read and increment the counter:
if (counter[val] >0) {
// duplicate
} else {
counter[val]++;
}
Use a HashSet
to hold all numbers already seen. It operates in (amortized) O(1)
time, so the total is O(N)
.
Scan the array 3 times:
A
. XOR together all the numbers from 0 to N-1 -> B
. Now A XOR B = X XOR D
, where X is the removed element, and D is the duplicate element.A XOR B
. XOR together all the array elements where this bit is set -> A1
. XOR together all the numbers from 0 to N-1 where this bit is set -> B1
. Now either A1 XOR B1 = X
or A1 XOR B1 = D
.A1 XOR B1
. If it is found, this is the duplicate element. If not, the duplicate element is A XOR B XOR A1 XOR B1
.