Problem. Call an array good if more than half of its elements are the same. The domain from which the elements are taken is not necessarily ordered like integers so one cannot make comparisons like “Is A[i] > A[j]?” or sort the array, but one can check whether two elements are the same in O(1) time.
Idea: a majority element must be majority in either of the two halves of an array.
Algorithm:
Count function: T(n)≤2T(2n)+O(1)=O(n)
MajorityElement function: T(n)≤2T(2n)+2⋅O(n)
First term: recursive calls
Second term: calls Count
Solution: T(n)=O(nlogn) (same recurrence relation as mergesort)
Correctness (Brief argument):
Base case: in n=1 the element is majority element
IH: Assume MajorityElement(k/2) is correct.
IS:
If one of them has no majority but the other ones does, the one with majority must be the true majority because of an element exists in more than half of the total array it must be that in one of the halves it will be the majority.
If both halves have a majority, then the one that has more counts in the total array wins
There cannot be a both halves no-majority case as explained in (1)