Given an array of integers, only sum the ones that appear once. Use a Counter from the collections module to count occurrences. Use list comprehension to retain unique numbers - sum the list.
The solution is as follows:
from collections import Counter
class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
counts = Counter(nums)
return sum([num for num in counts if counts[num] < 2])
_ Time Complexity:
O(n) - We iterate through the array to count all the integers.
_ Space Complexity:
O(n) - We store the count of each interger.