Majority Element
Python data engineering interview problem. Difficulty: beginner. Pattern: Hashing. About 10 minutes. Free to practice.
Find the element appearing more than n/2 times. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.
A majority value is an id or label that appears in more than half of a batch. The input guarantees that one exists, so you only need to find it. Return the value whose count is greater than n / 2. Do not return the most recent value or the first value. Count all occurrences, including ones that are far apart. Write the function majority_element(nums: list) -> int. In [3, 2, 3], the value 3 appears twice out of three positions, so the answer is 3. The starter file already has the function name and the harness print lines. Keep them, and fill only the function body.
Requirements
- Count occurrences across the complete list.
- Return the value appearing more than half the time.
- Return one integer value, not its count.
Constraints
- A majority element always exists.
- The list contains comparable values, and the return type is int.
Examples
Input: majority_element([3, 2, 3]) Output: 3 3 appears twice of three.
Topics: lakebench, python, majority, voting.
More Python interview questions · All interview problems · Learn data engineering
Majority Element
Interview-style drill: Find the element appearing more than n/2 times.
Implement `majority_element(nums: list) -> int`. Assume a majority always exists. Example: `[3, 2, 3]` → `3`. Keep the harness.