From ab979a607451382388f1da530b8ddc90b68b34ae Mon Sep 17 00:00:00 2001 From: alxkm Date: Sun, 13 Jul 2025 14:31:01 +0200 Subject: [PATCH 1/2] refactor: MajorityElement --- .../hashmap/hashing/MajorityElement.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) 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..7aee007c3c6e 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java @@ -1,7 +1,9 @@ package com.thealgorithms.datastructures.hashmap.hashing; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; +import java.util.Map; import java.util.List; /** @@ -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) { From 6b9122dd43ed470e0dfb3b6c58b91f9373e1da42 Mon Sep 17 00:00:00 2001 From: alxkm Date: Sun, 13 Jul 2025 14:33:35 +0200 Subject: [PATCH 2/2] refactor: fix import ordering --- .../datastructures/hashmap/hashing/MajorityElement.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 7aee007c3c6e..5fd6b2e7f3cb 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java @@ -3,8 +3,8 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; -import java.util.Map; import java.util.List; +import java.util.Map; /** * This class provides a method to find the majority element(s) in an array of integers.