Given an array of 2n elements of which n elements are same and the remaining n elements are all different. Write a C program to find out the value which is present n times in the array
I thought in the following way-
compare a[i] and a[i+1] and
compare a[i] and a[i+2]
and return element
this will run in O(n) time..can anyone give better solution?
I was going through some solutions where it is saying like this-
- Declare two variables a) count variable to keep track of count of majority element.
- Majority element.
- Do a for loop and repeat following steps 4-6 until end of array is reached.
- if current array element equals majority element, increment count
- else, if count is 0, update majority element with current array element and increment count.
- else if count is not 0 then decrement count.
- Do another for loop and count the number of occurrences of majority element in the array, if it’s half the array size then we have found the majority element, else there’s no majority element.
You can use the majority element algorithm as a basis for an O(n) solution with O(1) space.
You need space for one stored element. Pick the first element and store it, if the next element is the same as the stored one, you finished. If not, restart the algorithm from the next step. If you don’t find the element after the end of this, it means that the element are ordered in pairs like (a,b),(a,c),(a,d) or (b,a),(a,c),(a,d),(e,a).. Compare the first four elements and you have found the duplicate.
Since elements can be in arbitrary order, whichever first n/2 elements you check it’s possible that they are all different. So there is no solution which is bettern than O(n).