Sum of Repeated Numbers
easySave
ArrayCountingHash Table
Given an array of integers, find the sum of all integers that appear more than once in the array. The function should return the sum of these repeated numbers.
Example 1
Input
[ 1, 2, 3, 2, 4, 5, 5, 6 ]
Output
9
Explanation. The numbers 2 and 5 are repeated. 2 + 2 + 5 + 5 = 9.
Example 2
Input
[ 10, 20, 20, 20, 30 ]
Output
40
Explanation. The number 20 is repeated. 20 + 20 + 20 = 60 but only the sum of repeated numbers: 20 + 20 = 40.
Example 3
Input
[ 7, 8, 9, 10 ]
Output
0
Explanation. No numbers are repeated. The sum is 0.
Example 4
Input
[ 8, 8, 8, 8, 8 ]
Output
32
Explanation. The number 8 is repeated 5 times. 8 + 8 + 8 + 8 = 32.
Follow-up: How would the solution change if you need to count numbers that repeat a specific number of times, say exactly twice?
Constraints:
The input array will have at least one number and all elements will be integers.
- Views
- 3