algoadvance

Leetcode 1748. Sum of Unique Elements

Problem Statement

Given an integer array nums, return the sum of all the unique elements in the array. The unique elements of an array are the elements that appear exactly once in the array.

Clarifying Questions

  1. Can the input array contain negative numbers?
    • Yes, the array can contain negative numbers.
  2. What is the range of the input array length?
    • The length of the input array can range from 1 to 1000.
  3. What is the range of the element values in the array?
    • Each element can be in the range [-1000, 1000].

Strategy

To solve this problem, we’ll use a HashMap to count the occurrences of each element. Here’s the step-by-step strategy:

  1. Initialize a HashMap: Use it to count the occurrences of each element in the array.
  2. Count Occurrences: Traverse through the array and update the count for each element in the HashMap.
  3. Sum Unique Elements: Traverse through the HashMap and sum the elements that have a count of exactly one.
  4. Return the Result: Return the computed sum.

Code

public class SumOfUniqueElements {
    public int sumOfUnique(int[] nums) {
        Map<Integer, Integer> countMap = new HashMap<>();

        // Count occurrences of each element
        for (int num : nums) {
            countMap.put(num, countMap.getOrDefault(num, 0) + 1);
        }

        // Sum up the unique elements
        int sum = 0;
        for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
            if (entry.getValue() == 1) {
                sum += entry.getKey();
            }
        }

        return sum;
    }

    public static void main(String[] args) {
        SumOfUniqueElements obj = new SumOfUniqueElements();
        int[] nums = {1, 2, 3, 2};  // Example input
        System.out.println(obj.sumOfUnique(nums));  // Output should be 1 + 3 = 4
    }
}

Time Complexity

Space Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI