Tutorialspoint
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)
ArraysAlgorithmsPwCAdobe
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Initialize a count variable to 0 and a candidate variable to any value.

 Step 2: Iterate through the array and if count is 0, assign the current element as the candidate.
 Step 3: If the current element is equal to the candidate, increment the count.
 Step 4: If the current element is different from the candidate, decrement the count.
 Step 5: After the iteration, the candidate will be the majority element.
 Step 6: This algorithm works because the majority element appears more than n/2 times, so it will always have a positive final count.
 Step 7: The time complexity is O(n) as we traverse the array once, and the space complexity is O(1) as we only use two variables.

Submitted Code :