PPractick

DSA interview question

Majority Element II (More Than n/3 Times)

Hard · Algorithms · Topics: array, counting, boyer moore

The problem

A product survey lets users pick one favourite feature, and the team wants to highlight every feature chosen by more than a third of respondents. At most two features can clear that bar, since three features each with more than a third would add up to more than everyone. Extending Boyer–Moore voting to two candidates finds them in one pass with O(1) memory; a second pass then confirms which candidates really clear the threshold.

Example: [1, 1, 1, 3, 3, 2, 2, 2] → [1, 2].

Function signature

vector<int> majorityElement(const vector<int>& nums);  // all values appearing more than n/3 times, sorted

Test cases

Input numsOutputExplanation
[3, 2, 3][3]3 appears 2 > 1 times
[1][1]
[1, 2][1, 2]Each appears 1 > 0 times
[1, 1, 1, 3, 3, 2, 2, 2][1, 2]Each appears 3 > 2.67 times
[2, 2, 1, 3][2]2 appears 2 > 1.33 times
[1, 2, 3, 4][]Nobody clears the threshold

(Confirm: return every value appearing strictly more than ⌊n/3⌋ times, in sorted order; a majority is not guaranteed.)

How interviewers phrase it

Clarifying questions to ask

  1. Strictly more than n/3?
  2. Is the answer guaranteed to be non-empty?
  3. Does the output order matter?
  4. Is O(1) extra space required?

Follow-ups to expect

  1. "Why at most two answers?"
  2. "How do two counters work?"
  3. "Why is the verification pass necessary?"
  4. "How does it generalise to n/k?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in