Array has total 101 values. This array contains numbers from 1 to 100 and one number is repeating (two times). Write psuedo code to find repeating number.
A:
- You could hash the values and detect collisions
- You could sort the array then loop it finding duplicates
- You could search the array (long and slow!)
If you want to be smart, take a look at hashing. If you want to play it easy and safe, sorting the list with merge sort then looping the indexes would probably be best.
Tom Gullen
2010-08-05 10:13:37
Sorting the array would be O(N log N), and that's if you pick a decent sort algorithm. A linear search, with an array of "seen" flags, would be faster (O(N), and the operations trivial). That last part is key, though -- comparing each entry with every other is indeed "long and slow", so don't do it unless there's an O(1) way of answering the question "have i seen this number before?".
cHao
2010-08-05 10:33:52
How do you have a 'seen' flag though? That's the problem!
Tom Gullen
2010-08-05 10:58:52
@Tom Gullen: Would be trivial in languages that provide sets or dictionaries. Traverse the array, and add a number to a set if it is not already there. If it is, you have your duplicate.
Felix Kling
2010-08-05 13:00:46
A:
I'd add up all the indexes [0] -> [100] find out what 1 + 2 + 3 ... + 100 should equal subtract that from your result and you got the repeating number.
So you'd just have a simple
for
or while
loop going through each index then subtract the 2 and you have your result.
Something like...
q = 0;
p = 101 * 50;
for(i<=100; i <array.length; i++){
q += q + array[i]
}
repeating number = q-p;
Aidanc
2010-08-05 10:15:04
You don't even have to add all the numbers 1 to 100 to find out the total. It's simply 101 * 50 = 5050.
Guffa
2010-08-05 10:21:42
For reference, the easy way to calculate 1 + 2 + 3 + ... + 100 would be `(1 + 100) * 100/2`. Works for any two numbers; just replace `1` with the low number and `100` with the high one.
cHao
2010-08-05 10:21:48
@Darknight I simply answered the question, no more, no less. If you were to do that "divide and conquer"
Aidanc
2010-08-05 10:23:26
Or have an array of "this number's been seen" flags. Loop through the array, check the flag for that number. If it hasn't been set, set it and keep going; otherwise, you've found the number. This won't scale well to huge arrays (as it'll require at least some percentage of the array size for the flags), but for a few hundred (or even a few thousand), it should be fine.
cHao
2010-08-05 10:28:31
A:
Try this (C#):
int[] array = ... ; // initialize appropriately
var hashSet = new HashSet<int>();
var indexOfDuplicate = -1;
for (var i = 0; i < array.Length; i++) {
if (hashSet.Contains(array[i])) {
indexOfDuplicate = i;
break;
}
hashSet.Add(array[i]);
}
var duplicateNumber = array[indexOfDuplicate];
With this solution you will have both the index of the duplicate number (2nd occurrence) and the duplicate number.
John
2010-08-05 10:31:13