If I have an array of n length of unique values except one that is duplicated, what is the quickest way to find it?
e.g. [1, 2, 3, 4, 4, 10, 15, 12] quickest way to find that it is a 4. There could be millions of array elements.
If I have an array of n length of unique values except one that is duplicated, what is the quickest way to find it?
e.g. [1, 2, 3, 4, 4, 10, 15, 12] quickest way to find that it is a 4. There could be millions of array elements.
If you have feasibility to use Data Structure you can do it in CONSTANT time. i.e approx O(1). That is using a HashMap. (when we are dealing with millions of numbers)
You can also use a separate array say (Dummy) of size of max(element present in array) and then go on putting the element in the Dummy[element] and wherever you find the element is already present you achieve the desired result. It will also take O(n) complexity.
You have to go through all the elements of the array, one by one. Without more information there is no way to locate the repeated element without touching at least once each element. This is at least O(N)
and you can't go faster.
If the repeated elements are consecutive, for example [1,2,2,3], you can go one by one and compare it to the previous one; if they are equal you've found your element:
for (int i = 1; i < count; i++) {
if (arr[i] == arr[i-1]) {
std::cout << "found " << arr[i] << " at " << i << " and " << (i-1) << std::endl;
break;
}
}
If the repeated elements are not consecutive you can use a data structure to keep track of existing elements. When you find an element which has already been seen you inform that element:
initialize set to empty set;
for (i = 0; i < count; i++) {
if (arr[i] is in set) {
inform arr[i] as repeated element at position i;
break;
} else {
add arr[i] to set;
}
}
If the duplicate is in a completely random place, I don't see anyway around checking 1 by 1 until you find the duplicate at which point you would obviously stop.