Given an array of sorted ints, find the most common element in log (n)

It is easy to find the most common element in O (n). Is there a faster algorithm (O (logn)) for this? (if the array is sorted)

+6
source share
3 answers

It's impossible. The following is not a rigorous proof (rigorous proof of the lower bound is generally difficult), but reasonable reasoning.

Suppose your array always looks like 1, 2, 3, 4, 5, 6, ..., n. Then you are replacing a number of the appearance of the previous issue: 1, 2, 3, 3, 5, ... n. Now in the new array a[i] = ifor everyone i, except for one position.

, . , , , . , , one , .

+10

O(logn), , O(mlogn), m - .

, , m << n.

, 0 , , d, , , .

, maxCount, 0 . , endIndex - startIndex > maxCount, , maxCount endIndex - startIndex. , startIndex+1.

@ivan, O (n), .

+2

Python O(mlogn) @Parijat.

import bisect

def most_frequent_in_sorted(lst):
    most_frequent = None
    max_frequency = 0
    n = len(lst)
    idx = 0

    while idx < n:
        # Get leftmost index holding an element != lst[idx]
        next_leftmost_idx = bisect.bisect_right(lst, lst[idx])

        # Update most frequent element
        cur_frequency = next_leftmost_idx - idx
        if cur_frequency > max_frequency:
            most_frequent = lst[idx]
            max_frequency = cur_frequency

        # Update index to hold next different integer
        idx = next_leftmost_idx

    return most_frequent
0

All Articles