BudiBadu Logo

Sum of Unique Elements

Array Easy 25 views
Like3

You are presented with a list of integers representing entries collected from a busy day of customer orders. Some values appear once because they were single purchases, while others repeat due to bundled deals or recurring subscriptions. Your task is to identify the contribution made solely by the numbers that show up exactly one time. Think of these solitary values as special signatures left by unique customers whose actions should be recognized individually.

Picture each integer as a colored bead on a long strand. Some colors glitter brightly only once, while others blend into clusters of identical shades. If you were curating an art display, you would want to highlight the beads that stand alone because they offer contrast and tell a distinct story. In your array, these standout beads are the numbers that deserve attention, and their combined value expresses the weight of singular contributions.

By focusing on those individual appearances, you gain insight into the exclusive moments hidden within the data. A repeated value speaks of routine and patterns, but a unique value marks a rare event worthy of special notice. Before you present the final report, you must total only these unique elements and deliver the sum that celebrates them. Handle empty lists gracefully, and remember that a collection filled with duplicates might still hide a single remarkable number.

Example 1:

Input: nums = [1,2,3,2]
Output: 4
Explanation: Only 1 and 3 appear once, so their sum is 4.

Example 2:

Input: nums = [4,4,4]
Output: 0
Explanation: Every number repeats, leaving no unique contributions.

Example 3:

Input: nums = [0,5,-5,5,9]
Output: 4
Explanation: The unique numbers 0, -5, and 9 add up to 4.

Algorithm Flow

Recommendation Algorithm Flow for Sum of Unique Elements - Budibadu
Recommendation Algorithm Flow for Sum of Unique Elements - Budibadu

Best Answers

java
import java.util.*;
class Solution {
    public int sum_of_unique(Object nums) {
        if (nums == null) return 0;
        int[] arr;
        if (nums instanceof int[]) {
            arr = (int[]) nums;
        } else if (nums instanceof List) {
             List<?> list = (List<?>) nums;
             arr = new int[list.size()];
             for(int i=0; i<list.size(); i++) arr[i] = (int) list.get(i);
        } else {
            return 0;
        }
        
        Map<Integer, Integer> map = new HashMap<>();
        for (int n : arr) {
            map.put(n, map.getOrDefault(n, 0) + 1);
        }
        int sum = 0;
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() == 1) {
                sum += entry.getKey();
            }
        }
        return sum;
    }
}