public class MajorityElement { public static int findMajority(int[] nums) { int count = 0, candidate = -1; for (int num : nums) { if (count == 0) { candidate = num; } count += (num == candidate) ? 1 : -1; } return candidate; } public static void main(String[] args) { int[] arr = {2, 2, 1, 1, 1, 2, 2}; System.out.println(findMajority(arr)); } }
The algorithm picks a candidate and counts its occurrences against others. Here, 2 appears 4 times out of 7, which is more than half, so the output is 2.
The count increases when the current element matches the candidate and decreases otherwise, effectively tracking the difference between candidate occurrences and others.
public class MajorityElement { public static int findMajority(int[] nums) { int count = 0, candidate = 0; for (int num : nums) { if (count == 0) { candidate = num; } if (num == candidate) { count++; } else { count--; } } return candidate; } public static void main(String[] args) { int[] arr = {}; System.out.println(findMajority(arr)); } }
The code returns 0 because candidate is initialized to 0 and the loop does not run. No exception is thrown.
Moore's Voting Algorithm finds a candidate that might be majority. To confirm, count its occurrences and verify it exceeds half the array size.
public class MajorityElement { public static int findMajority(int[] nums) { int count = 0, candidate = -1; for (int num : nums) { if (count == 0) { candidate = num; } count += (num == candidate) ? 1 : -1; } return candidate; } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 3, 6}; System.out.println(findMajority(arr)); } }
The algorithm returns 3 as candidate after processing, but since no element appears more than half, it is not a true majority.
