Tutorialspoint
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:

  1. Takes an array of integers as input
  2. 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)
AlgorithmsGoldman SachsSamsung
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 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

Steps to solve by this approach:

 Step 1: Initialize count = 0 and candidate = null
 Step 2: Iterate through each element in the array
 Step 3: If the count is 0, assign the current element as the candidate
 Step 4: If the current element equals the candidate, increment count; otherwise, decrement count
 Step 5: Return the final candidate as the majority element

Submitted Code :