Talentd
FleetCode
Make and follow sheets.Sign in

Sum of Unique Elements solution and explanation

EasyArrayCountingHash Table5 min read80.4% acceptanceUpdated 9 Apr 2026
Sum of Unique Elements (LeetCode 1748) | Full solution with a frequency arrayNikhil Lohia · 12:00 · 3K viewsWatch on YouTube
9 more videos on this problem
  1. Sum of Unique Elements (LeetCode 1748) | Full solution with a frequency arrayNikhil Lohia · 12:00 · 3K views
  2. Leetcode | 1748. Sum of Unique Elements | Easy | Java SolutionDeveloper Docs · 5:18 · 1K views
  3. Leetcode Solution - 1748 Sum of Unique ElementsJohn Leonardo · 3:08 · 1K views
  4. Leetcode 1748 - Sum of Unique Elementsblake · 9:34 · 1K views
  5. 1748. Sum of Unique Elements (Leetcode Easy)Programming Live with Larry · 3:14 · 902 views
  6. leetcode - 1748 Sum of Unique Elements Explanation and SolutionlitCode · 6:06 · 602 views
  7. How to Solve "1748 Sum of Unique Elements" on LeetCode? - JavascriptBecoming A Better Dev (with David) · 6:09 · 551 views
  8. 1748 Sum of Unique Elements - LeetCode Pair Programming in JavaBecoming A Better Dev (with David) · 34:24 · 254 views
  9. LeetCode 1748 | Sum of Unique Elements | Counting Array | JavaSleepy Cracker · 2:03 · 226 views
  10. 1748. Sum of Unique Elements - Leetcode - Hashmap- C++ Tutorialcodetutorial4you · 5:13 · 179 views

The problem

You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array.

Return the sum of all the unique elements of nums.

Example 1:

Input: nums = [1,2,3,2]
Output: 4
Explanation: The unique elements are [1,3], and the sum is 4.

Example 2:

Input: nums = [1,1,1,1,1]
Output: 0
Explanation: There are no unique elements, and the sum is 0.

Example 3:

Input: nums = [1,2,3,4,5]
Output: 15
Explanation: The unique elements are [1,2,3,4,5], and the sum is 15.

Constraints:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100

Approach overview

Problem Overview: You receive an integer array nums. The task is to compute the sum of elements that appear exactly once in the array. Any number that appears more than once must be ignored. The challenge is efficiently identifying which values have frequency 1.

Approach 1: Frequency Count and Sum (O(n) time, O(n) space)

This approach uses a frequency map to count how many times each number appears. Iterate through the array once and store counts in a hash table. Then iterate over the frequency map and add values whose count equals 1. Hash table lookup and insertion both run in constant time on average, so the entire operation is linear. This method is straightforward and widely used in problems involving element frequency tracking. It relies on a hash table for constant-time updates and works well for unsorted arrays.

The key insight is separating counting from summation. Instead of trying to determine uniqueness while iterating, first build a complete frequency distribution. Once you know exact counts, computing the result becomes trivial. This pattern appears frequently in problems involving duplicates, histograms, or occurrence tracking.

Approach 2: Single Pass with Multiple Sets (O(n) time, O(n) space)

This approach tracks numbers using two sets during a single traversal. Maintain a unique set for numbers seen exactly once and a duplicates set for numbers seen more than once. As you iterate through the array, check whether the number has been seen before. If it appears for the first time, insert it into unique. If it appears again, remove it from unique and add it to duplicates. At the end, sum all values remaining in unique.

The advantage is that counting and filtering happen simultaneously in one pass. Set membership checks and updates are constant time on average because they use hashing internally. This technique is common when you need to dynamically maintain "seen once" vs "seen multiple times" elements. It still uses hashing internally, making it conceptually similar to the counting approach but slightly more dynamic.

Both strategies operate in linear time and rely on efficient lookups provided by a hash table. Since the input is simply an array, the algorithm focuses on tracking frequencies rather than modifying structure or order. Problems involving frequency counting are often categorized under counting techniques.

Recommended for interviews: The frequency counting approach is usually the expected solution. It is simple, easy to reason about, and clearly demonstrates understanding of hash maps and counting patterns. The set-based single-pass method is equally efficient but slightly less common. Interviewers typically want to see the frequency map solution first because it generalizes well to many duplicate-handling problems.

Approach 1: Frequency Count and Sum

In this approach, we maintain a frequency count of each number using a hash map (or array if constraints are small). By keeping track of these counts, we can identify which numbers occur exactly once. A second pass over the frequency data allows us to sum the unique elements efficiently.

def sum_of_unique(nums):
    count = {}
    for num in nums:
        count[num] = count.get(num, 0) + 1
    return sum(num for num, cnt in count.items() if cnt == 1)

nums = [1, 2, 3, 2]
print("Output:", sum_of_unique(nums))
import java.util.HashMap;
import java.util.Map;

public class Solution {
    public static int sumOfUnique(int[] nums) {
        Map<Integer, Integer> count = new HashMap<>();
        for (int num : nums) {
            count.put(num, count.getOrDefault(num, 0) + 1);
        }
        int sum = 0;
        for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
            if (entry.getValue() == 1) {
                sum += entry.getKey();
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 2};
        System.out.println("Output: " + sumOfUnique(nums));
    }
}
#include <iostream>
#include <vector>
#include <unordered_map>

int sumOfUnique(std::vector<int>& nums) {
    std::unordered_map<int, int> count;
    for (int n : nums) {
        count[n]++;
    }
    int sum = 0;
    for (const auto& [num, cnt] : count) {
        if (cnt == 1) {
            sum += num;
        }
    }
    return sum;
}

int main() {
    std::vector<int> nums = {1, 2, 3, 2};
    std::cout << "Output: " << sumOfUnique(nums) << std::endl;
    return 0;
}
function sumOfUnique(nums) {
    const count = {};
    for (let num of nums) {
        count[num] = (count[num] || 0) + 1;
    }
    let sum = 0;
    for (let num in count) {
        if (count[num] === 1) {
            sum += Number(num);
        }
    }
    return sum;
}

const nums = [1, 2, 3, 2];
console.log("Output:", sumOfUnique(nums));
#include <stdio.h>

int sumOfUnique(int* nums, int numsSize) {
    int count[101] = {0};
    for (int i = 0; i < numsSize; i++) {
        count[nums[i]]++;
    }
    int sum = 0;
    for (int i = 0; i < 101; i++) {
        if (count[i] == 1) {
            sum += i;
        }
    }
    return sum;
}

int main() {
    int nums[] = {1, 2, 3, 2};
    int numsSize = sizeof(nums) / sizeof(nums[0]);
    printf("Output: %d\n", sumOfUnique(nums, numsSize));
    return 0;
}
using System;
using System.Collections.Generic;

class Solution {
    public static int SumOfUnique(int[] nums) {
        var count = new Dictionary<int, int>();
        foreach (var num in nums) {
            if (count.ContainsKey(num)) {
                count[num]++;
            } else {
                count[num] = 1;
            }
        }
        int sum = 0;
        foreach (var kvp in count) {
            if (kvp.Value == 1) {
                sum += kvp.Key;
            }
        }
        return sum;
    }

    static void Main() {
        int[] nums = {1, 2, 3, 2};
        Console.WriteLine("Output: " + SumOfUnique(nums));
    }
}

In this Python solution, a dictionary is used for counting occurrences. The function sums all numbers with a count of one from the dictionary.

Complexity

Time Complexity: O(n) with n being the input array length. Space Complexity: O(n) due to the dictionary storage.

Try this approach in the editor

Approach 2: Single Pass with Multiple Sets

This approach involves using two sets: one to track all elements and another to track duplicates. As we iterate over the array, we determine if an element is being seen for the first time or if it has been repeated. The strategy involves set operations to track and sum unique values concurrently.

def sum_of_unique(nums):
    seen = set()
    duplicates = set()
    sum_ = 0
    for num in nums:
        if num not in seen:
            if num not in duplicates:
                sum_ += num
                seen.add(num)
        else:
            if num not in duplicates:
                sum_ -= num
                duplicates.add(num)
    return sum_

nums = [1, 2, 3, 2]
print("Output:", sum_of_unique(nums))
import java.util.HashSet;

public class Solution {
    public static int sumOfUnique(int[] nums) {
        HashSet<Integer> seen = new HashSet<>();
        HashSet<Integer> duplicates = new HashSet<>();
        int sum = 0;
        for (int num : nums) {
            if (!seen.contains(num)) {
                if (!duplicates.contains(num)) {
                    seen.add(num);
                    sum += num;
                }
            } else {
                if (!duplicates.contains(num)) {
                    sum -= num;
                    duplicates.add(num);
                }
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 2};
        System.out.println("Output: " + sumOfUnique(nums));
    }
}
#include <iostream>
#include <unordered_set>
#include <vector>

int sumOfUnique(std::vector<int>& nums) {
    std::unordered_set<int> seen, duplicates;
    int sum = 0;
    for (int n : nums) {
        if (seen.find(n) == seen.end()) {
            if (duplicates.find(n) == duplicates.end()) {
                seen.insert(n);
                sum += n;
            }
        } else {
            if (duplicates.find(n) == duplicates.end()) {
                sum -= n;
                duplicates.insert(n);
            }
        }
    }
    return sum;
}

int main() {
    std::vector<int> nums = {1, 2, 3, 2};
    std::cout << "Output: " << sumOfUnique(nums) << std::endl;
    return 0;
}
function sumOfUnique(nums) {
    const seen = new Set();
    const duplicates = new Set();
    let sum = 0;
    for (const num of nums) {
        if (!seen.has(num)) {
            if (!duplicates.has(num)) {
                seen.add(num);
                sum += num;
            }
        } else {
            if (!duplicates.has(num)) {
                sum -= num;
                duplicates.add(num);
            }
        }
    }
    return sum;
}

const nums = [1, 2, 3, 2];
console.log("Output:", sumOfUnique(nums));
#include <stdio.h>
#include <stdbool.h>
#define MAX 101

int sumOfUnique(int* nums, int numsSize) {
    int set[MAX] = {0};
    int dup[MAX] = {0};
    int sum = 0;
    for (int i = 0; i < numsSize; i++) {
        int num = nums[i];
        if (!set[num] && !dup[num]) {
            sum += num;
            set[num] = 1;
        } else if (set[num] && !dup[num]) {
            sum -= num;
            dup[num] = 1;
        }
    }
    return sum;
}

int main() {
    int nums[] = {1, 2, 3, 2};
    int numsSize = sizeof(nums) / sizeof(nums[0]);
    printf("Output: %d\n", sumOfUnique(nums, numsSize));
    return 0;
}
using System;
using System.Collections.Generic;

class Solution {
    public static int SumOfUnique(int[] nums) {
        var seen = new HashSet<int>();
        var duplicates = new HashSet<int>();
        int sum = 0;
        foreach (var num in nums) {
            if (!seen.Contains(num)) {
                if (!duplicates.Contains(num)) {
                    seen.Add(num);
                    sum += num;
                }
            } else {
                if (!duplicates.Contains(num)) {
                    sum -= num;
                    duplicates.Add(num);
                }
            }
        }
        return sum;
    }

    static void Main() {
        int[] nums = {1, 2, 3, 2};
        Console.WriteLine("Output: " + SumOfUnique(nums));
    }
}

This Python method uses sets to track seen items and duplicates. As it iterates through the list, a conditional update manages the sum.

Complexity

Time Complexity: O(n) owing to traversing the list once. Space Complexity: O(n) due to the sets storage.

Try this approach in the editor

Approach 3: Default Approach

function sumOfUnique(nums: number[]): number {
    const cnt = new Array(101).fill(0);
    for (const x of nums) {
        ++cnt[x];
    }
    let ans = 0;
    for (let x = 0; x < 101; ++x) {
        if (cnt[x] == 1) {
            ans += x;
        }
    }
    return ans;
}
func sumOfUnique(nums []int) (ans int) {
	cnt := [101]int{}
	for _, x := range nums {
		cnt[x]++
	}
	for x := 0; x < 101; x++ {
		if cnt[x] == 1 {
			ans += x
		}
	}
	return
}
impl Solution {
    pub fn sum_of_unique(nums: Vec<i32>) -> i32 {
        let mut cnt = [0; 101];
        for x in nums {
            cnt[x as usize] += 1;
        }
        let mut ans = 0;
        for x in 1..101 {
            if cnt[x] == 1 {
                ans += x;
            }
        }
        ans as i32
    }
}
class Solution {
    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function sumOfUnique($nums) {
        $sum = 0;
        for ($i = 0; $i < count($nums); $i++) {
            $hashtable[$nums[$i]] += 1;
            if ($hashtable[$nums[$i]] == 1) {
                $sum += $nums[$i];
            }
            if ($hashtable[$nums[$i]] == 2) {
                $sum -= $nums[$i];
            }
        }
        return $sum;
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Frequency Count and Sum

Time Complexity: O(n) with n being the input array length. Space Complexity: O(n) due to the dictionary storage.

Single Pass with Multiple Sets

Time Complexity: O(n) owing to traversing the list once. Space Complexity: O(n) due to the sets storage.

Default Approach–

Complexity analysis

ApproachTimeSpaceWhen to Use
Frequency Count and SumO(n)O(n)General case when counting occurrences in an unsorted array
Single Pass with Multiple SetsO(n)O(n)When you want to track unique vs duplicate elements dynamically in one traversal

Frequently asked questions

Is Sum of Unique Elements easy or hard?

Sum of Unique Elements is classified as an Easy problem on LeetCode with a high acceptance rate around 80%. The logic mainly involves counting occurrences using a hash table and filtering values with frequency equal to one.

Sum of Unique Elements Python/Java solution

In Python, a dictionary or collections.Counter can track element frequencies, then sum keys with count equal to 1. In Java, a HashMap<Integer, Integer> stores counts during iteration and a second loop calculates the result.

How to solve Sum of Unique Elements in O(n)?

Traverse the array and store counts in a hash table. After counting, iterate through the map and add numbers whose frequency equals 1. Because both counting and summation steps are linear, the overall complexity remains O(n).

What is the best approach for Sum of Unique Elements?

The most common solution uses a hash map to count frequencies of each number. After building the frequency table in O(n) time, iterate through it and sum values that appear exactly once. This approach is simple, reliable, and optimal for unsorted arrays.

Is Sum of Unique Elements asked at Google/Amazon/Meta?

Frequency counting problems like Sum of Unique Elements commonly appear in coding interviews at companies such as Amazon, Google, and Meta. They test understanding of hash tables, duplicate handling, and efficient linear-time processing.

What data structure is used in Sum of Unique Elements?

The primary data structure is a hash table (or dictionary/map) used to store the frequency of each number. Some solutions also use hash sets to track numbers seen once versus multiple times. Both rely on constant-time average lookups.

What is the time complexity of Sum of Unique Elements?

The optimal solution runs in O(n) time where n is the length of the array. Each element is processed once to build a frequency map, and hash table operations like insert and lookup take constant time on average. Space complexity is O(n) due to storing counts.

Comments

Now write it yourselfClose this page and solve Sum of Unique Elements in the editor, without looking.
Practise Sum of Unique Elements