Skip to content

1748. Sum of Unique Elements 👍

  • Time: $O(n)$
  • Space: $O(100) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int sumOfUnique(vector<int>& nums) {
    constexpr int kMax = 100;
    int ans = 0;
    vector<int> count(kMax + 1);

    for (const int num : nums)
      ++count[num];

    for (int i = 1; i <= kMax; ++i)
      if (count[i] == 1)
        ans += i;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int sumOfUnique(int[] nums) {
    final int kMax = 100;
    int ans = 0;
    int[] count = new int[kMax + 1];

    for (final int num : nums)
      ++count[num];

    for (int i = 1; i <= kMax; ++i)
      if (count[i] == 1)
        ans += i;

    return ans;
  }
}
1
2
3
4
5
class Solution:
  def sumOfUnique(self, nums: list[int]) -> int:
    return sum(num
               for num, freq in collections.Counter(nums).items()
               if freq == 1)