Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Moore's voting algorithm is added #5770

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,16 +1,73 @@
package com.thealgorithms.datastructures.hashmap.hashing;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
/*
This class finds the majority element(s) in an array of integers.
This class finds the majority element(s) in an array/List of integers.
A majority element is an element that appears more than or equal to n/2 times, where n is the length
of the array.
*/
public final class MajorityElement {
private MajorityElement() {
private MajorityElement(){}

/**
* This method uses Moore's voting algorithm to find the majority element in the list.
* If a majority element is present, it returns the element; otherwise, it returns Optional.empty().
* @param <T> The type of elements in the list
* @param elements List of any type
* @return Optional of majority element or empty if none found
*/
public static <T> Optional<T> majorityElement(List<T> elements) {
if (elements == null || elements.isEmpty()) {
return Optional.empty(); // Handle empty list case
}

T currentElement = elements.get(0);
long frequency = 1;

// Moore's Voting Algorithm to find potential majority element
for (int i = 1; i < elements.size(); i++) {
if (frequency == 0) {
currentElement = elements.get(i);
frequency = 1;
} else if (!currentElement.equals(elements.get(i))) {
frequency--;
} else {
frequency++;
}
}

// Second pass to confirm if it occurs more than n/2 times
long count = 0;
for (T element : elements) {
if (element.equals(currentElement)) {
count++;
}
}

if (count > elements.size() / 2) {
return Optional.of(currentElement);
} else {
return Optional.empty();
}
}

/**
* Method to handle array input and convert to list.
* @param <T> The type of elements in the array
* @param elements Array of any type
* @return Optional of majority element or empty if none found
*/
public static <T> Optional<T> majorityElement(T[] elements) {
if (elements == null || elements.length == 0) {
return Optional.empty(); // Handle empty array case
}
return majorityElement(Arrays.asList(elements));
}

/*
This method returns the majority element(s) in the given array of integers.
@param nums: an array of integers
Expand Down
Loading