Sum of Unique Elements
LeetCode 1848 | Difficulty: Easyβ
EasyProblem Descriptionβ
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`
Topics: Array, Hash Table, Counting
Approachβ
Hash Mapβ
Use a hash map for O(1) average lookups. Store seen values, frequencies, or indices. The key question: what should I store as key, and what as value?
When to use
Need fast lookups, counting frequencies, finding complements/pairs.
Solutionsβ
Solution 1: C# (Best: 150 ms)β
| Metric | Value |
|---|---|
| Runtime | 150 ms |
| Memory | 35.5 MB |
| Date | 2022-01-17 |
Solution
public class Solution {
public int SumOfUnique(int[] nums) {
int[] freq = new int[101];
foreach(var item in nums)
{
freq[item]++;
}
int sum = 0;
for(int i=0;i<101;i++)
{
if(freq[i]==1) sum += i;
}
return sum;
}
}
π 1 more C# submission(s)
Submission (2022-01-17) β 153 ms, 36.1 MBβ
public class Solution {
public int SumOfUnique(int[] nums) {
int[] freq = new int[101];
int sum = 0;
foreach(var item in nums)
{
freq[item]++;
if(freq[item]==1) sum += item;
if(freq[item]==2) sum -= item;
}
return sum;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Hash Map | $O(n)$ | $O(n)$ |
Interview Tipsβ
Key Points
- Start by clarifying edge cases: empty input, single element, all duplicates.
- Hash map gives O(1) lookup β think about what to use as key vs value.
- LeetCode provides 1 hint(s) for this problem β try solving without them first.
π‘ Hints
Hint 1: Use a dictionary to count the frequency of each number.