Similar Problems
Similar Problems not available
Sum Of Unique Elements - Leetcode Solution
Companies:
LeetCode: Sum Of Unique Elements Leetcode Solution
Difficulty: Easy
Topics: hash-table array
Problem:
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 is no unique element, so the sum is 0.
Solution:
We can solve this problem by first creating a dictionary to count the frequency of each number in the input array. Then, we can iterate through the dictionary and sum up all the unique elements - those whose frequency is 1.
Here is the detailed step by step solution:
-
Create a dictionary to count the frequency of each number in the input array.
freq = {} for num in nums: if num in freq: freq[num] += 1 else: freq[num] = 1
-
Iterate through the dictionary and sum up all the unique elements.
sum = 0 for key in freq: if freq[key] == 1: sum += key
-
Return the sum.
return sum
Complete Solution:
class Solution: def sumOfUnique(self, nums: List[int]) -> int: # Create a dictionary to count the frequency of each number in the input array. freq = {} for num in nums: if num in freq: freq[num] += 1 else: freq[num] = 1
# Iterate through the dictionary and sum up all the unique elements.
sum = 0
for key in freq:
if freq[key] == 1:
sum += key
# Return the sum.
return sum
Time Complexity: O(n) where n is the length of the input array.
Space Complexity: O(n) for the dictionary to store the frequency of each number.
Sum Of Unique Elements Solution Code
1