Problem Description
Given an integer array, the task is to calculate and return the sum of all unique elements in the array (i.e., the elements that appear exactly once).
Key Insights
- Use a hash table (or dictionary) to count the frequency of each number.
- Iterate through the table and add only those numbers with a frequency of one.
- The problem constraints allow an efficient O(n) solution.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the input array, since we traverse the array to count frequencies and then iterate over the counts. Space Complexity: O(n) in the worst-case scenario, due to the additional data structure used for counting frequencies.
Solution
We use a hash table (or dictionary) to count how many times each element appears in the array. Once the counts have been computed, we iterate over the hash table and sum the elements that appear exactly once. This approach leverages efficient lookup in the hash table, ensuring the solution runs in linear time relative to the size of the input.