1748. Sum of Unique Elements LeetCode Solution
In this guide, you will get 1748. Sum of Unique Elements LeetCode Solution with the best time and space complexity. The solution to Sum of Unique Elements problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Sum of Unique Elements solution in C++
- Sum of Unique Elements solution in Java
- Sum of Unique Elements solution in Python
- Additional Resources
Problem Statement of Sum of Unique Elements
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
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(100) = O(1)
1748. Sum of Unique Elements LeetCode Solution in C++
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;
}
};
/* code provided by PROGIEZ */
1748. Sum of Unique Elements LeetCode Solution in Java
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;
}
}
// code provided by PROGIEZ
1748. Sum of Unique Elements LeetCode Solution in Python
class Solution:
def sumOfUnique(self, nums: list[int]) -> int:
return sum(num
for num, freq in collections.Counter(nums).items()
if freq == 1)
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.