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 indexn // 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 thatstatistics.modereturns 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.