DSA interview question
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].
vector<int> majorityElement(const vector<int>& nums); // all values appearing more than n/3 times, sorted
Input nums | Output | Explanation |
|---|---|---|
[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.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in