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
- Boyer-Moore voting algorithm
- Track candidate and count
- If count=0, new candidate
Related Arrays exercises
Practice all Arrays exercises · Run this idea in the Java compiler