#1748

Sum of Unique Elements

Easy
ArrayHash TableCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a hash map allows us to count occurrences of each element efficiently, enabling us to find the unique elements in a single pass.

⚙️

Algorithm

2 steps
  1. 1Step 1: Create a hash map to count the frequency of each element.
  2. 2Step 2: Iterate through the hash map and sum the keys that have a value of 1.
solution.py4 lines
1def sumOfUnique(nums):
2    from collections import Counter
3    count = Counter(nums)
4    return sum(num for num, freq in count.items() if freq == 1)

Complexity note: The time complexity is O(n) because we traverse the array once to build the hash map and then iterate over the map, which is efficient. The space complexity is O(n) due to the storage of the hash map.

  • 1Using a hash map allows for efficient counting of elements.
  • 2Unique elements can be identified by their frequency being exactly one.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.