Sum of Unique Elements - Problem

You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array.

Return the sum of all the unique elements of nums.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,2]
Output: 4
💡 Note: Elements 1 and 3 appear exactly once, so sum = 1 + 3 = 4. Element 2 appears twice so it's not unique.
Example 2 — All Unique
$ Input: nums = [1,2,3,4,5]
Output: 15
💡 Note: All elements appear exactly once, so sum = 1 + 2 + 3 + 4 + 5 = 15
Example 3 — No Unique Elements
$ Input: nums = [1,1,2,2,3,3]
Output: 0
💡 Note: Every element appears exactly twice, so no element is unique. Sum = 0

Constraints

  • 1 ≤ nums.length ≤ 100
  • -100 ≤ nums[i] ≤ 100

Visualization

Tap to expand
Sum of Unique Elements INPUT nums = [1, 2, 3, 2] 1 idx 0 2 idx 1 3 idx 2 2 idx 3 Count Frequency: 1 appears: 1 time 2 appears: 2 times 3 appears: 1 time Length: 4 elements ALGORITHM STEPS 1 Initialize HashMap Create map for counts 2 Count Frequencies Single pass through array 3 Find Unique (count=1) Filter elements appearing once 4 Sum Unique Elements Add all unique values HashMap State: {1: 1, 2: 2, 3: 1} Unique Elements: 1 and 3 (count = 1) Sum = 1 + 3 = 4 FINAL RESULT Unique Elements Identified: 1 2 3 2 Unique (count=1) Duplicate (count>1) Calculation: 1 + 3 = 4 (skip duplicate 2s) OUTPUT 4 OK - Sum computed! Key Insight: One-Pass Optimized approach uses a HashMap to count frequencies in O(n) time. Then iterate through the map to sum elements with count exactly equal to 1. Time Complexity: O(n) | Space Complexity: O(n) for the HashMap TutorialsPoint - Sum of Unique Elements | One-Pass Optimized Approach
Asked in
Amazon 35 Google 28
89.2K Views
Medium Frequency
~10 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen