Let's take an array of n integers. No integer repeats itself except one.
Given:
a. If n is even then the repeating integer is repeated n/2 times. ( That is count of repeating integer is equal to the count of non repeating integers)
b. If n is odd the repeating integer is repeated (n-1)/2 times or (n+1)/2.( That is count of repeating integer is one greater than or one less than the count of non repeating integers)
c. The repeating integer is never placed side by side in the array.
How to find out the repeating integer?
General method of finding the repeating integer is : creating a binary tree from the given integers. Whenever we encounter a duplicate integer, we can stop building the binary tree and return the repeating integer.
For the given special case, we can use the same algorithm. There are many possible permutations for the input array. If first and third integer same then it will take only three integers to be inspected to find out the repeating element.
So, what is the worst case for above problem. Lets create a permutation where we encounter the repeating integer 2 times as far as possible from the starting point.
If the count of repeating integer is one more then the non-repeating integers, that would have permutations like the one given below.
i. start here->1,2,1,3,1,4,1,5,1,6,1,7,1 ---- We can identify 1 as repeating integer after inspecting 3 integers.
If the count of repeating integer is equal to the non-repeating integers, that would have permutations like the two examples given below.
ii. start here->1,2,1,3,1,4,1,5,1,6,1,7 ---- We can identify 1 as repeating integer after inspecting 3 integers.
iii. start here->2,1,3,1,4,1,5,1,6,1,7,1 ---- We can identify 1 as repeating integer after inspecting 4 integers.
If the count of repeating integer is one less then the non-repeating integers, that would have permutations like the examples given below.
iv. start here->1,2,3,4,1 ---- We can identify 1 as repeating integer after inspecting 5 integers.
v. start here-> 2,3,1,4,1 ---- We can identify 1 as repeating integer after inspecting 5 integers.
Now we can generalize. If the count of repeating integer is two less then the non-repeating integers, that would have permutations like the examples given below (not limited to).
vi. start here-> 1,2,3,4,5,1 ---- We can identify 1 as repeating integer after inspecting 6 integers.
vii. start here-> 2,3,4,1,5,1 ---- We can identify 1 as repeating integer after inspecting 6 integers.
So for the given problem we have to inspect at most 5 integers from the array.
A general formula:
If the count of repeating integer is x less then the non-repeating integers then we have to inspect at most x+4 integers from the array for n greater than equal to 5.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment