Java ProgramsArraysFind Majority Element in an Array

Find Majority Element in an Array in Java

advanced·  Arrays  ·  Array

Problem

A majority element is one that appears more than n/2 times in an array of length n — strictly more than every other value combined.

Given an array of integers that is guaranteed to contain a majority element, find it.

Input
[4, 4, 2, 4, 6, 4, 4]
Output
Majority element: 4

Java Program

Java
public class MajorityElement { public static void main(String[] args) { int[] arr = {4, 4, 2, 4, 6, 4, 4}; int candidate = arr[0]; int count = 1; for (int i = 1; i < arr.length; i++) { if (count == 0) { // vote canceled out, switch to a new candidate candidate = arr[i]; count = 1; } else if (arr[i] == candidate) { count++; // vote for the current candidate } else { count--; // vote against the current candidate } } System.out.println("Majority element: " + candidate); } }

Output

Majority element: 4

Core Logic

Treating matching values as votes for a candidate and mismatches as votes against it, a single running candidate survives every non-majority value canceling itself out.

How It Works
  1. 1candidate starts as the first element, with count at 1.
  2. 2If count ever drops to 0, the current element becomes the new candidate, and count resets to 1.
  3. 3An element equal to candidate increments count; any other element decrements it.
  4. 4Because the true majority element outnumbers every other value combined, it's mathematically guaranteed to survive as the final candidate.
Scanning [4, 4, 2, 4, 6, 4, 4], count dips down to 1 after the 2 and 6 are seen, but candidate stays 4 throughout and finishes with count = 3.
💡

Key Point: This algorithm assumes a majority element actually exists — given an array with no true majority, it would still confidently report some candidate, just an incorrect one, since nothing here double-checks the final count against n/2.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: A single pass tracks just a candidate value and a running vote count, with no extra data structure needed.

Key Concepts

Boyer-Moore voting algorithmcandidate and countsingle pass

Approach 2: Frequency Map

Java
import java.util.HashMap; import java.util.Map; public class MajorityElementFrequency { public static void main(String[] args) { int[] arr = {4, 4, 2, 4, 6, 4, 4}; Map<Integer, Integer> freq = new HashMap<>(); int majority = arr[0]; for (int num : arr) { int count = freq.getOrDefault(num, 0) + 1; freq.put(num, count); if (count > arr.length / 2) { // crossed the majority threshold majority = num; } } System.out.println("Majority element: " + majority); } }

Output

Majority element: 4

Core Logic

Counting every value's occurrences directly, and checking each running count against n/2 as it grows, finds the majority element without relying on the voting trick's cancellation insight.

How It Works
  1. 1A HashMap<Integer, Integer> named freq tracks each value's running count as the array is scanned.
  2. 2freq.getOrDefault(num, 0) + 1 computes the updated count for the current value.
  3. 3As soon as a value's count exceeds arr.length / 2, it's recorded as the majority element.
  4. 4Unlike the voting algorithm, this doesn't need the guarantee that a majority exists — a count simply never crosses the threshold if there isn't one.
Scanning [4, 4, 2, 4, 6, 4, 4], the count for 4 keeps climbing and crosses 7 / 2 = 3 once its fourth occurrence is seen.
💡

Key Point: This trades the voting algorithm's O(1) space for O(n), in exchange for not needing to assume a majority element exists ahead of time — the count crossing the threshold is verified directly.

Complexity
Time Complexity: O(n)Space Complexity: O(n)

Why: The map holds one entry per distinct value in the array, up to n in the worst case, alongside the single pass used to build it.

Key Concepts

HashMapgetOrDefault()threshold check

Approach 3: Java 8

Java
import java.util.Arrays; import java.util.Map; import java.util.stream.Collectors; public class MajorityElementStream { public static void main(String[] args) { int[] arr = {4, 4, 2, 4, 6, 4, 4}; // Groups by value, counts occurrences, then picks the entry with the highest count int majority = Arrays.stream(arr) .boxed() .collect(Collectors.groupingBy(n -> n, Collectors.counting())) .entrySet() .stream() .max(Map.Entry.comparingByValue()) .get() .getKey(); System.out.println("Majority element: " + majority); } }

Output

Majority element: 4

Core Logic

Grouping every value by identity and counting occurrences, then picking the entry with the highest count, finds the majority element declaratively — without the voting trick's cancellation insight or a hand-written frequency map.

How It Works
  1. 1Arrays.stream(arr).boxed() turns the primitive array into a Stream<Integer>.
  2. 2Collectors.groupingBy(n -> n, Collectors.counting()) builds a Map<Integer, Long> of each value's occurrence count.
  3. 3entrySet().stream().max(Map.Entry.comparingByValue()) finds the entry with the highest count.
  4. 4.get().getKey() extracts that entry's key — the value that occurred most often.
Grouping [4, 4, 2, 4, 6, 4, 4] by identity gives counts 4: 4, 2: 1, 6: 2; the entry with the highest count, 4, is reported.
💡

Key Point: Like the voting algorithm, this trusts the problem's guarantee that a true majority exists — it reports whichever value has the highest count even if that count doesn't actually exceed n/2, since nothing here checks the count against that threshold.

Complexity
Time Complexity: O(n)Space Complexity: O(n)

Why: groupingBy() visits every element once to build a map holding one entry per distinct value, and finding the max entry afterward only scans those distinct entries.

Key Concepts

StreamCollectors.groupingBy()Collectors.counting()Map.Entry.comparingByValue()

Related Programs