1. Base case
A single element is the majority of its own length-1 range.
if (left === right) return nums[left]Typorithm · medium
Step 1 of 8 · intro card
Divide & Conquer
Find each half's majority candidate; if they differ, count both across the range and keep the larger.
The majority element appears more than half the time, so it must be the majority of at least one half.
Recurse to get each half's candidate; if they match, it is the answer immediately.
When they disagree, a linear count over the range decides which candidate dominates.
Majority of the whole is majority of a half.
Agreeing halves settle it instantly.
Disagreeing halves need a count.
function majorityElement(nums, left = 0, right = nums.length - 1) {
if (left === right) return nums[left];
const mid = Math.floor((left + right) / 2);
const leftMajor = majorityElement(nums, left, mid);
const rightMajor = majorityElement(nums, mid + 1, right);
if (leftMajor === rightMajor) return leftMajor;
let leftCount = 0;
let rightCount = 0;
for (let i = left; i <= right; i += 1) {
if (nums[i] === leftMajor) leftCount += 1;
if (nums[i] === rightMajor) rightCount += 1;
}
return leftCount > rightCount ? leftMajor : rightMajor;
}Connect each part of the code to the concept before you type.
A single element is the majority of its own length-1 range.
if (left === right) return nums[left]Find the majority candidate of each half independently.
const rightMajor = majorityElement(nums, mid + 1, right)If both halves agree, that element is the overall majority.
if (leftMajor === rightMajor) return leftMajorWhen halves disagree, count each candidate across the full range.
if (nums[i] === leftMajor) leftCount += 1The candidate that appears more often in this range wins.
return leftCount > rightCount ? leftMajor : rightMajorRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputNumbers 2,2,1,2,3,2,2 · majority guaranteed
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state