Majority Element in Java: Explanation & Practice

Find element appearing more than n/2 times

Problem summary

Find the element that appears more than n/2 times in the array (guaranteed to exist).

Starter code

public class Main {
    public static void main(String[] args) {
        int[] arr = {3, 3, 4, 2, 4, 4, 2, 4, 4}; // Test case 1
        
        // Find majority element
        // Print: Majority: <element>
    }
}

Expected output and test cases

  • 4 appears 5 times
    Majority: 4
  • All same
    Majority: 1
  • 2 is majority
    Majority: 2

Hints

  1. Boyer-Moore voting algorithm
  2. Track candidate and count
  3. If count=0, new candidate

Related Arrays exercises

Practice all Arrays exercises · Run this idea in the Java compiler