Sum of Unique Elements
Given an array of integers, calculate the sum of all the unique elements. An element is considered unique if it appears exactly once in the array.
[ 4, 5, 5, 4, 6 ]
Explanation. Elements 4 and 5 appear more than once, while 6 appears only once. Therefore, the sum of unique elements is 6.
[ 9, 3, 3, 9, 5 ]
Explanation. Here 9 and 3 are repeating, and only 5 is unique with a sum of 5.
[ 7, 7, 7, 7 ]
Explanation. All elements are repeats. There are no unique values, hence the sum is 0.
[ 1, 2, 3, 4 ]
Explanation. All elements in the array are unique. The sum therefore equals 1+2+3+4 = 10.
Follow-up: Can you extend your solution to manage a stream of numbers and constantly report the sum of unique elements?
1. The array will contain at least one element.\n2. All elements will be integers.
- Views
- 2