Algorithms · Visualized
Majority Element
Divide & Conquer
Break a problem into independent subproblems, solve each, and combine the answers.
Finds the element that appears more than n/2 times in an array. Time: O(n log n) average, O(n log n) — note the Boyer-Moore Voting Algorithm solves this in O(n), D&C is a teaching alternative worst; space: O(log n) — recursion stack.
Big-O: Classic D&C recursions: Merge Sort, Quick Sort, Maximum Subarray, Fast Power.
Majority Element (Divide & Conquer)
Divide & ConquerFinds the element that appears more than n/2 times in an array. Using divide and conquer: split the array in half, find the majority candidate of each half recursively, and if they differ, count actual occurrences of each candidate in the combined range to decide the true majority.
How Majority Element Works
- Base case: if the array has one element, it is trivially the majority element of that single-element range.
- Split the array into left and right halves.
- Recursively find the majority candidate of the left half and of the right half.
- If both halves agree on the same candidate, that's the majority element for the combined range.
- If they disagree, count how many times each candidate actually appears across the full combined range, and return whichever count is higher.
Majority Element Worked Example
Input: [2, 2, 1, 1, 1, 2, 2]
Split into [2,2,1,1] and [1,2,2]. Left half recursively resolves to majority candidate 2 (or a tie broken by counting). Right half resolves to 2. Both agree on 2 → combined majority candidate is 2. Verifying: 2 appears 4 times out of 7, more than half — confirmed majority element is 2.
def majority_element(a):
cand, count = None, 0
for v in a:
if count == 0:
cand, count = v, 1
elif v == cand:
count += 1
else:
count -= 1
return candBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Majority Element Time & Space Complexity
When to Use Majority Element
- Teaching how divide-and-conquer 'combine' steps sometimes require extra verification work, unlike simpler merge steps.
- Voting/consensus systems needing to identify a dominant choice among many votes.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.