Data Structures19 sections · 729 units
Open in Course

Application: Range Majority

Element appearing > half

Find an element appearing more than (rl+1)/2(r - l + 1) / 2 times in A[l..r]A[l..r], or report none exists. Observation: If a majority exists, it's either:

  • The median (quantile query)
  • Or we can verify a candidate in O(logσ)O(\log \sigma)

Algorithm:

1.1. Find median using kthSmallest

2.2. Count its frequency

3.3. If frequency >(rl+1)/2> (r - l + 1) / 2, return it

4.4. Otherwise, no majority exists.

Time: O(logσ)O(\log \sigma) for single query. This works because the majority element, if it exists, must be the median.