Sum of Unique Elements — LeetCode 1748 Python Solution

EasyArrayHash TableCounting
Problem
#1748
Pattern
Hash Map
Reading time
2 min

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.

Example

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

Python solution

Python
class Solution:
    def sumOfUnique(self, nums: List[int]) -> int:
        cnt = Counter(nums)
        return sum(x for x, v in cnt.items() if v == 1)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1748. Sum of Unique Elements is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1748. Sum of Unique Elements?
LeetCode 1748. Sum of Unique Elements is rated Easy on LeetCode.
What is the time complexity of LeetCode 1748. Sum of Unique Elements?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1748. Sum of Unique Elements?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1748. Sum of Unique Elements cover?
LeetCode 1748. Sum of Unique Elements is tagged Array, Hash Table and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview