diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java index 915e4228b618..5fd6b2e7f3cb 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java @@ -1,8 +1,10 @@ package com.thealgorithms.datastructures.hashmap.hashing; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; +import java.util.Map; /** * This class provides a method to find the majority element(s) in an array of integers. @@ -18,13 +20,18 @@ private MajorityElement() { * Returns a list of majority element(s) from the given array of integers. * * @param nums an array of integers - * @return a list containing the majority element(s); returns an empty list if none exist + * @return a list containing the majority element(s); returns an empty list if none exist or input is null/empty */ public static List majority(int[] nums) { - HashMap numToCount = new HashMap<>(); + if (nums == null || nums.length == 0) { + return Collections.emptyList(); + } + + Map numToCount = new HashMap<>(); for (final var num : nums) { numToCount.merge(num, 1, Integer::sum); } + List majorityElements = new ArrayList<>(); for (final var entry : numToCount.entrySet()) { if (entry.getValue() >= nums.length / 2) {