InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Majority Element

easy Original ↗ 00:00

Problem

Given an integer array nums of length n, return the value that appears more than ⌊n/2⌋ times. You may assume the majority element always exists in the array.

Follow-up: solve it in linear time and O(1) space.

Examples

  • Input: nums = [3, 2, 3] → Output: 3 3 appears twice, and 2 > ⌊3/2⌋ = 1.
  • Input: nums = [2, 2, 1, 1, 1, 2, 2] → Output: 2 2 appears 4 times out of 7, and 4 > ⌊7/2⌋ = 3.
  • Input: nums = [6] → Output: 6 A single element is trivially the majority.

Constraints

  • 1 <= n <= 5 * 10^4
  • -10^9 <= nums[i] <= 10^9
  • A majority element (count > ⌊n/2⌋) is guaranteed to exist

The follow-up requires O(n) time with O(1) space.

Think about it first

Hint 1 The obvious tool is a hash map of counts. What are its time and space costs?
Hint 2 If you sorted the array, where must the majority element appear? Consider what "more than half" forces.
Hint 3 Pair each occurrence of the majority value with one occurrence of any other value and delete both. Since the majority has more than half, it cannot be fully cancelled. Applying that cancellation with a single candidate and a counter is Boyer–Moore voting.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug