
Problem
Solution
Submissions
Majority Element
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a C program to find the majority element in an array. The majority element is the element that appears more than ⌊n/2⌋ times, where n is the size of the array. You may assume that the majority element always exists in the array.
Example 1
- Input: nums = [3,2,3]
- Output: 3
- Explanation: The element 3 appears twice, which is more than n/2 = 3/2 = 1.5 times. Therefore, 3 is the majority element.
Example 2
- Input: nums = [2,2,1,1,1,2,2]
- Output: 2
- Explanation: The element 2 appears 4 times, which is more than n/2 = 7/2 = 3.5 times. Therefore, 2 is the majority element.
Constraints
- 1 ≤ nums.length ≤ 5 * 10^4
- -10^9 ≤ nums[i] ≤ 10^9
- The majority element always exists in the array
- Time Complexity: O(n)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use Boyer-Moore Voting Algorithm to find the majority element in O(n) time and O(1) space
- Initialize a candidate element and a counter
- Traverse the array, updating the candidate and counter based on the current element
- When the counter becomes 0, choose a new candidate
- The final candidate will be the majority element