Tutorialspoint
Problem
Solution
Submissions

Find Majority Element (Boyer-Moore Algorithm)

Certification: Basic Level Accuracy: 66.67% Submissions: 6 Points: 8

Write a Java program to find the majority element in an array of integers using the Boyer-Moore Voting Algorithm.

Example 1
  • Input: nums = [3,2,3]
  • Output: 3
  • Explanation:
    • 3 appears 2 times → majority of 3 elements
Example 2
  • Input: nums = [2,2,1,1,1,2,2]
  • Output: 2
  • Explanation:
    • 2 appears 4 times → majority of 7 elements
Constraints
  • 1 ≤ nums.length ≤ 5 * 10^4
  • -10^9 ≤ nums[i] ≤ 10^9
  • A majority element is guaranteed
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysAlgorithmsShopifyPhillips
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 which works in two passes.
  • First pass establishes a candidate for the majority element.
  • Second pass verifies if the candidate is actually the majority element.
  • The algorithm is optimal in terms of both time and space complexity.
  • No need for additional data structures like HashMap.

Steps to solve by this approach:

 Step 1: Initialize count to 0 and candidate to null.

 Step 2: Iterate through the array. If count is 0, set the current element as the candidate.
 Step 3: If the current element equals the candidate, increment count; otherwise, decrement count.
 Step 4: After the first pass, we have a candidate for the majority element.
 Step 5: Verify the candidate is indeed the majority element by counting its occurrences.
 Step 6: If the count is greater than n/2, return the candidate; otherwise, return -1.
 Step 7: Since the problem states there's always a majority element, we'll always return the candidate from step 4.

Submitted Code :