From dcb02c61dfadd6cab986c44c2999aec7fea7076a Mon Sep 17 00:00:00 2001 From: Oleksandr Klymenko Date: Tue, 15 Jul 2025 18:10:06 +0300 Subject: [PATCH] refactor: `MajorityElement` (#6380) * refactor: MajorityElement * refactor: fix import ordering --------- Co-authored-by: Deniz Altunkapan <93663085+DenizAltunkapan@users.noreply.github.com> --- .../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 915e4228b..5fd6b2e7f 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 @@ public final class 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) {