Sum of Distinct Elements
MediumPractice library · +20 XPrecursionhashingarrays
Given a list of N integers, compute the sum of all distinct elements in the list. Each distinct number should be added to the sum exactly once, regardless of how many times it appears in the input.
Input
The first line contains an integer N, the number of elements. The second line contains N space-separated integers, the elements of the list.
Output
Print a single integer, the sum of the distinct elements.
Constraints
1 <= N <= 200000. Each integer is between -10^9 and 10^9.
Time limit 1 s (native code; slower languages get more)Memory 256 MB15 hidden tests
Example 1
Input
5 1 2 2 3 1
Output
6
The distinct elements are 1, 2, and 3. Their sum is 1 + 2 + 3 = 6.
Example 2
Input
4 10 20 10 20
Output
30
The distinct elements are 10 and 20. Their sum is 10 + 20 = 30.
Hints
Similar problems
- Subsegment Sum Divisible by KMedium
- Count Pairs with Equal Digit SumMedium
- Count Pairs with Sum Divisible by KMedium
- Subarray with Target ProductMedium
- Longest Subarray with At Most K Duplicate PairsMedium
- Distinct Consecutive PairsMedium
More topics: Arrays problems, Hash Map and Hashing problems, Recursion problems
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
5 1 2 2 3 1
Example 2 input
4 10 20 10 20