BudiBadu Logo

Sum of Unique Elements

Array Easy 94 views
Like3

In Sum of Unique Elements, you receive an integer array and need one final number: the sum of values that appear exactly once. Any number that appears two or more times should contribute zero to the result, even if it appears in separate parts of the array.

A reliable approach is frequency counting. First pass: count each value in a hash map/dictionary. Second pass over that map (or the array): add only values whose count is 1. This keeps the logic easy to read and matches what the judge expects across mixed inputs, all-duplicate inputs, and empty arrays.

The checker also verifies behavior with negative and positive integers together, so treat all integers uniformly. Your function should return a single integer and avoid side effects. The output is deterministic: same input always yields the same sum. This challenge is a solid warm-up for map-based counting patterns that appear often in practical coding tasks and interview-style data processing questions. Keep the return type strictly numeric in every platform template.

Examples

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
15
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;
    }
}