
Problem
Solution
Submissions
Majority Element in an Array
Certification: Basic Level
Accuracy: 50%
Submissions: 4
Points: 8
Write a C# program to find the majority element in an array. The majority element is defined as the element that appears more than ⌊n/2⌋ times in the array, where n is the size of the array. You may assume that the majority element always exists in the array.
Implement the FindMajorityElement(int[] nums) function which:
- Takes an array of integers as input
- Returns the majority element
Example 1
- Input: nums = [3, 2, 3]
- Output: 3
- Explanation:
- The element 3 appears 2 times in the array of size 3, which is more than ⌊3/2⌋ = 1.
Example 2
- Input: nums = [2, 2, 1, 1, 1, 2, 2]
- Output: 2
- Explanation:
- The element 2 appears 4 times in the array of size 7, which is more than ⌊7/2⌋ = 3.
Constraints
- 1 <= nums.length <= 5 * 10⁴
- -10⁹ <= nums[i] <= 10⁹
- 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 the Boyer-Moore Voting Algorithm
- Initialize count = 0 and candidate = null
- For each element in the array, if count is 0, set candidate = current element
- If current element is same as candidate, increment count; otherwise, decrement count
- The final candidate will be the majority element