Majority, Mode and Median
The last group of problems of this chapter comes from statistics: finding the majority element, the mode and the median of a set of numbers. For each of them, there is an obvious quadratic solution, a better one based on sorting, and room for something smarter. They are excellent exercises to practise designing divide and conquer algorithms: this lesson develops the median completely, and leaves the divide and conquer versions of the majority element and the mode as challenges, with hints.
- Three statistical problems, and how to improve them step by step: brute force, sorting, and divide and conquer.
- Quickselect, which finds the median (or any order statistic) in linear time on average, by "half" a Quicksort.
- Why divide and conquer does not always need to solve all the subproblems.
The Majority Element
Problem. Given a vector of elements, is there a majority element, that is, an element that appears more than half of the times (at least times)? If so, which one?
For example, in 4 5 5 1 5 2 5 5, the 5 appears 5 times out of 8, and : it is the majority element. In 4 5 5 1 5 2 5 1, no element reaches 5 appearances: there is no majority element. Note that there can be at most one majority element.
Brute force:
For each element, count how many times it appears in the vector. A small improvement: if the majority element exists, it must appear among the first positions (otherwise, it would not fit enough times in the rest), so only those candidates need to be counted. It is still quadratic.
public boolean hasMajorityNaive(int[] v) {
int n = v.length;
int threshold = n / 2 + 1;
for (int i = 0; i < n / 2 + 1; i++) {
int counter = 0;
for (int j = i; j < n; j++)
if (v[j] == v[i]) counter++;
if (counter >= threshold) return true;
}
return false;
}
Sorting:
If the vector is sorted, equal elements are contiguous, and a majority element occupies more than half of the positions, so it must occupy the central position. Sort (a copy of) the vector, take the central element as the only candidate, and count its appearances:
public boolean hasMajoritySorting(int[] v) {
int[] copy = v.clone(); // do not modify the caller's array
Arrays.sort(copy); // O(n log n)
int candidate = copy[copy.length / 2];
int counter = 0;
for (int x : copy) // O(n)
if (x == candidate) counter++;
return counter >= copy.length / 2 + 1;
}
Divide and conquer: a challenge
Can we avoid sorting? Here are some hints for a divide and conquer solution:
- Pair up the elements: compare with , with , and so on. If the two elements of a pair are different, discard both; if they are equal, keep one of them.
- If the original vector has a majority element, it is still the majority element of the reduced vector (think about why: discarding two different elements can never remove more appearances of the majority element than of all the others together).
- The reduced vector has at most half of the elements: apply the same idea to it, recursively. What happens when the length is odd?
- The process returns a candidate, not a certainty: a final linear pass must check that the candidate really appears more than times.
What are , and for this algorithm, and what is its complexity?
The Mode
Problem. The mode of a set of numbers is the element that is repeated the most times (the predominant element). For example, in 1 2 5 1 5 2 6 1, the 1 appears three times, more than any other number: it is the mode. Unlike the majority element, the mode always exists (although it may not be unique).
Brute force:
For each element, count its appearances in the rest of the vector, and keep the one with the highest count.
Sorting:
After sorting, equal elements are contiguous, so a single linear pass that counts the length of each run of equal elements finds the mode:
public int[] calculateModeSorting(int[] v) {
int[] copy = v.clone();
Arrays.sort(copy); // O(n log n)
int mode = copy[0], maxRepetitions = 1, current = 1;
for (int i = 1; i < copy.length; i++) { // O(n)
if (copy[i] == copy[i - 1]) {
current++;
if (current > maxRepetitions) {
mode = copy[i];
maxRepetitions = current;
}
} else {
current = 1; // a new run starts
}
}
return new int[]{mode, maxRepetitions}; // the mode and its frequency
}
Divide and conquer: a challenge
A divide and conquer solution can be designed with the ideas of Quicksort. Hints:
- Choose a pivot and partition the vector into three groups: elements smaller than, equal to and greater than the pivot. The size of the middle group is the number of repetitions of the pivot.
- The mode is either the pivot, or it is inside one of the other two groups. Which groups is it worth exploring? Can a group be discarded if it has fewer elements than the best frequency found so far?
- How does the cost depend on the number of different values in the vector?
The Median
Problem. The median of a list of numbers is the value that would be in the middle position if the list were sorted: half of the elements are smaller (or equal) and half are greater (or equal). For example, the median of 4 5 6 1 3 2 7 is 4: sorted, the list is 1 2 3 4 5 6 7. (For an even number of elements, we take, for example, the element at position .)
The median is a robust measure of the "center" of data: unlike the average, it is not distorted by a few extreme values. It is also the ideal pivot for Quicksort.
Sorting:
The direct solution follows the definition: sort (a copy of) the vector and take the central element.
public int medianBySorting(int[] v) {
int[] copy = v.clone();
Arrays.sort(copy);
return copy[copy.length / 2];
}
But sorting does much more work than necessary: it puts all the elements in order, while we only need one of them.
Divide and conquer: Quickselect
The idea, due to Tony Hoare (the inventor of Quicksort), is to reuse the partition of Quicksort. After partitioning around a pivot, the pivot is in its final position , with the smaller elements on its left and the greater ones on its right. We are looking for the element that belongs to position . Then:
- if , the pivot is the median;
- if , the median is in the left part: search there, and discard the right part;
- if , the median is in the right part: search there, and discard the left part.
Unlike Quicksort, only one of the two parts needs to be processed.
public int medianQuickselect(int[] v) {
int[] copy = v.clone();
return quickselect(0, copy.length - 1, copy, copy.length / 2);
}
private int quickselect(int left, int right, int[] v, int k) {
if (left == right) return v[left]; // a single element
int p = Util.partition(v, left, right); // the pivot ends at position p
if (p == k) return v[p]; // found
else if (p > k) return quickselect(left, p - 1, v, k); // only the left part
else return quickselect(p + 1, right, v, k); // only the right part
}
The repository version of partition takes the central element as pivot, moves it to the beginning, moves every element smaller than or equal to it to the left, and finally places the pivot between both groups. With 4 5 6 1 3 2 7 (, so we look for position ):
| Call | Pivot | Vector after the partition | Pivot position | Decision |
|---|---|---|---|---|
| positions 0 to 6 | 1 | 1 5 6 4 3 2 7 | 0 | : search the right part |
| positions 1 to 6 | 4 | 1 2 3 4 6 5 7 | 3 | : the median is 4 |
Two partitions were enough, and the elements 5, 6 and 7 were never ordered among themselves.
Analysis
Each call partitions its part in linear time and continues with one subproblem.
- Best and average case. If the pivot divides the part into two halves, there is one subproblem of size : , , . Since (): . The total work is . With random pivots, the parts are not exactly halves, but a probabilistic analysis shows that the average case is still .
- Worst case. If the pivot is always at an extreme, the problem shrinks by one element at each step: , , , so , as in Quicksort.
In practice, Quickselect is much faster than sorting. We measured both with 2 million random integers: Quickselect found the median in about 37 ms, while Arrays.sort needed about 330 ms to sort the copy.
There is a famous algorithm, the median of medians (Blum, Floyd, Pratt, Rivest and Tarjan, 1973), that chooses a pivot guaranteed to be "good enough" (it divides the vector into groups of 5, takes the median of each group, and recursively the median of those medians). It makes the selection even in the worst case. Its constants are high, so in practice randomised Quickselect is usually preferred, but it proved that selection is fundamentally easier than sorting.
🧠 Checkpoint: Selection versus sorting
Question: You need the 10 largest values of a list of 100 million numbers. Would you sort the list?
Answer: No. With Quickselect you can find the element that would be in position in linear average time; after that partition, the 10 largest elements are exactly those to its right (in any order), and sorting just those 10 is trivial. Another good option is a min-heap of size 10, traversing the list once: . Sorting the whole list, , does far more work than needed.
- Confusing the majority element with the mode. A majority element appears more than times; the most frequent element may not.
- Sorting to find a single element. Quickselect finds the median in on average.
- Recursing into both parts in Quickselect. Only the part that contains the position you are looking for is needed.
- Forgetting the worst case of Quickselect. It is , like Quicksort.
Summary
| Problem | Brute force | Sorting | Divide and conquer |
|---|---|---|---|
| Majority element | challenge: pair elements and keep candidates | ||
| Mode | challenge: partition into smaller, equal and greater | ||
| Median | sort and take the middle: | Quickselect: on average, worst case |
- Sorting is a powerful first step: it groups equal elements and places each element in its position, which simplifies many problems.
- But sorting often does more than needed. Quickselect reuses the partition of Quicksort and processes only the part that contains the answer, reaching linear average time.
- Divide and conquer does not always need to solve all the subproblems: discarding the ones that cannot contain the solution is what makes binary search and Quickselect fast.
Practice
- 👑 Majority element. Implement the divide and conquer algorithm described in the hints, and validate it with a stress test against the sorting version. Analyze its complexity.
- 📊 Mode. Implement the divide and conquer algorithm for the mode based on three-way partitions. How does it behave when all the elements are different? And when there are only three different values?
- 🎯 k-th element. Generalize Quickselect to find the -th smallest element for any , and use it to compute the first and third quartiles of a vector.
- ⏱️ Measure. Compare the times of the median by sorting and by Quickselect for random integers. How does the ratio between both evolve?
- 🔴 Worst case. With the repository's
partition(central pivot), construct an input of size 8 for which Quickselect needs the maximum number of partitions to find the median.
Errors, suggestions and public questions open a form on GitHub, visible to everyone.