Skip to content

Commit e621b61

Browse files
committed
Feature: Moore's voting algorithm is added to find majority element in List/Array
1 parent 6682c7c commit e621b61

File tree

1 file changed

+59
-2
lines changed

1 file changed

+59
-2
lines changed

src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,73 @@
11
package com.thealgorithms.datastructures.hashmap.hashing;
22

33
import java.util.ArrayList;
4+
import java.util.Arrays;
45
import java.util.HashMap;
56
import java.util.List;
7+
import java.util.Optional;
68
/*
7-
This class finds the majority element(s) in an array of integers.
9+
This class finds the majority element(s) in an array/List of integers.
810
A majority element is an element that appears more than or equal to n/2 times, where n is the length
911
of the array.
1012
*/
1113
public final class MajorityElement {
12-
private MajorityElement() {
14+
private MajorityElement(){}
15+
16+
/**
17+
* This method uses Moore's voting algorithm to find the majority element in the list.
18+
* If a majority element is present, it returns the element; otherwise, it returns Optional.empty().
19+
* @param <T> The type of elements in the list
20+
* @param elements List of any type
21+
* @return Optional of majority element or empty if none found
22+
*/
23+
public static <T> Optional<T> majorityElement(List<T> elements) {
24+
if (elements == null || elements.isEmpty()) {
25+
return Optional.empty(); // Handle empty list case
26+
}
27+
28+
T currentElement = elements.get(0);
29+
long frequency = 1;
30+
31+
// Moore's Voting Algorithm to find potential majority element
32+
for (int i = 1; i < elements.size(); i++) {
33+
if (frequency == 0) {
34+
currentElement = elements.get(i);
35+
frequency = 1;
36+
} else if (!currentElement.equals(elements.get(i))) {
37+
frequency--;
38+
} else {
39+
frequency++;
40+
}
41+
}
42+
43+
// Second pass to confirm if it occurs more than n/2 times
44+
long count = 0;
45+
for (T element : elements) {
46+
if (element.equals(currentElement)) {
47+
count++;
48+
}
49+
}
50+
51+
if (count > elements.size() / 2) {
52+
return Optional.of(currentElement);
53+
} else {
54+
return Optional.empty();
55+
}
56+
}
57+
58+
/**
59+
* Method to handle array input and convert to list.
60+
* @param <T> The type of elements in the array
61+
* @param elements Array of any type
62+
* @return Optional of majority element or empty if none found
63+
*/
64+
public static <T> Optional<T> majorityElement(T[] elements) {
65+
if (elements == null || elements.length == 0) {
66+
return Optional.empty(); // Handle empty array case
67+
}
68+
return majorityElement(Arrays.asList(elements));
1369
}
70+
1471
/*
1572
This method returns the majority element(s) in the given array of integers.
1673
@param nums: an array of integers

0 commit comments

Comments
 (0)