10. Majority Element
easyAsked at N26Find the element that appears more than n/2 times in an array. N26 frames this as detecting the dominant currency in a multi-currency batch.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array nums of size n, return the majority element which always appears more than floor(n/2) times. You may assume the majority element always exists.
Constraints
n == nums.length1 <= n <= 5 * 10^4Majority element is guaranteed to exist
Examples
Example 1
nums=[3,2,3]3Example 2
nums=[2,2,1,1,1,2,2]2Approaches
1. Hash map count
Count each element, return the one whose count exceeds n/2.
- Time
- O(n)
- Space
- O(n)
const m = new Map();
for (const x of nums) m.set(x, (m.get(x)||0)+1);
for (const [k,v] of m) if (v > nums.length/2) return k;Tradeoff:
2. Boyer-Moore voting
Maintain a candidate and a count; flip candidate when count hits zero. The true majority survives every cancellation pass.
- Time
- O(n)
- Space
- O(1)
function majorityElement(nums) {
let cand = 0, count = 0;
for (const n of nums) {
if (count === 0) cand = n;
count += (n === cand) ? 1 : -1;
}
return cand;
}Tradeoff:
N26-specific tips
N26 likes the Boyer-Moore answer because O(1) memory matches how their stream processors flag the dominant currency in a multi-currency settlement window without buffering.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Majority Element and other N26 interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →