Algorithm to output for a length m of a number stream, the value of the element j appearing in the stream for which freq[j]>m/2 with space complexity O(1) and time complexity O(m). Dont need to worry about the case when there are no elements with freq > m/2.
The question in simpler terms:
In a collection of 'M' elements, some elements are repeated. Find the element which occurred at least M/2 times.
Approach:
Initialize an array B[] of size 32 for storing bit counts.
Iterate through all the elements in the given array A[] of length m.
for each A[i] (0 <= i <= m-1), get all the positions where the bit is set and increment the corresponding positions in Array B.
Suppose Array A = {3,5,7,5};
Then after we have seen all the elements of A, Array B would look like:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 2 4
Now iterate through B and set "1" if B[i] > (m/2) else set 0. - Above m=4 so m/2 = 2;
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 => 5
So the element >= m/2 is 5 in array A.
Code:
Input:
int [] A = {7,11,8,11,9,11,7,11,8,11,9,11};
Output:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 2 8 10
Majority: 11
No comments:
Post a Comment