We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Sum of Unique Elements

Number: 1848

Difficulty: Easy

Paid? No

Companies: Meta, Apple


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.


Code Solutions

# Function to sum unique elements in the list
def sum_of_unique(nums):
    # Create a dictionary to count occurrence of each number
    frequency = {}
    for num in nums:
        # Increase the count for the number
        frequency[num] = frequency.get(num, 0) + 1

    # Sum only those numbers that appear exactly once
    unique_sum = 0
    for num, count in frequency.items():
        if count == 1:
            unique_sum += num
    return unique_sum

# Example usage:
# nums = [1,2,3,2]
# print(sum_of_unique(nums))  # Output: 4
← Back to All Questions