9. Majority Element
easyAsked at FreshworksFind the agent ID assigned to more than half the open tickets — a Boyer-Moore voting drill that Freshworks dresses up as automation-rule triage.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array nums of size n, return the majority element — the element that appears more than n/2 times. You may assume a majority element always exists.
Constraints
1 <= n <= 5 * 10^4Majority element is guaranteedSolve in linear time and constant space
Examples
Example 1
nums = [3,2,3]3Example 2
nums = [2,2,1,1,1,2,2]2Approaches
1. Brute force with Map
Count each element and return the one with count > 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
Track a candidate and a count. On match, count++. On mismatch, count--. When count hits 0, swap the candidate. Survivor is the majority.
- Time
- O(n)
- Space
- O(1)
function majorityElement(nums) {
let candidate = null, count = 0;
for (const n of nums) {
if (count === 0) candidate = n;
count += (n === candidate) ? 1 : -1;
}
return candidate;
}Tradeoff:
Freshworks-specific tips
Freshworks wants Boyer-Moore by name — say 'voting algorithm' explicitly and justify why the candidate survives because the majority outvotes everyone else combined.
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 Freshworks interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →