Sum of Unique Elements
Easy About 8 min Free, no account needed
Sum the values that appear exactly once in the array.
The brief
Given an integer array nums, return the sum of the values that appear
exactly once.
[1, 2, 3, 2], only1and3are unique, so the answer is4.- If nothing is unique the answer is
0.
The obvious approach decides "is this value unique?" by re-scanning the whole array for every element, O(n2). The hidden test has 200,000 distinct values; the rescan approach does twenty billion comparisons, far too slow. You need O(n).
Starter code
using System;
public class Solution
{
// TODO: return the sum of the values that occur exactly once in nums.
public long SumOfUnique(int[] nums)
{
throw new NotImplementedException();
}
}How it is graded
Visible examples help you iterate. Hidden tests then cover edge cases and larger inputs, and every test reports server-measured time and allocated bytes.
What it practices
- Hash maps and sets
- Trade memory for constant-time lookups, membership tests and frequency counts.
Related katas
- Contains Duplicate Easy Free Decide whether an array contains any repeated value.
- Count Distinct Letters Easy Free How many different letters appear? A 26-slot array already knows.
- Count Pairs With Difference K Easy Free Count the pairs of indices whose values differ by exactly k.
- Isomorphic Strings Easy Free Can one string be turned into the other by a consistent character substitution?