Skip to the solution
EasyDSA12 min read

How do you find the majority element?

302 views

The problem

Question presented to candidate: "Given a list of integers, return the majority element โ€” the value that appears more than n/2 times. First assume one always exists, then tell me what changes if it might not. Please code it in Python and aim for O(1) extra space."

What a strong answer should cover:

  • The definition: more than โŒŠn/2โŒ‹ occurrences, so at most one majority can exist; exactly half is not a majority.
  • The simple answers: counting with a dict/Counter (O(n) time, O(n) space) and sorting then taking index n // 2 (O(n log n)).
  • Boyer-Moore voting: one candidate and one counter, O(n) time and O(1) space, with the cancelling-pairs argument for why it is correct.
  • The verification pass when a majority is not guaranteed ([1, 2, 3] yields candidate 3).
  • Python specifics: Counter(nums).most_common(1), nums.count(candidate) for the verify pass, // for floor division, and that statistics.mode returns the most common value, which is not necessarily a majority.

Clarifying questions expected:

  • Is a majority guaranteed? What should be returned if there is none?

Code / implementation expected: Yes โ€” a Boyer-Moore majority(nums) in Python with an optional verify pass, run on inputs with and without a majority.

  • arrays
  • boyer-moore

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonBoyer-Moore voting with a verify pass on seven inputs
PythonTrace of the vote, the no-majority trap, and vote vs count vs sort

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 33 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

How do you check if a linked list is a palindrome?

Continue