Unique Elements Counter - Problem

Given an array of integers, identify all unique elements (elements that appear exactly once) and count the duplicate elements (elements that appear more than once).

Use a set data structure to efficiently track which elements you have seen before.

Return: An array containing two integers: [number_of_unique_elements, number_of_duplicate_elements]

Input & Output

Example 1 — Mixed Elements
$ Input: nums = [1,2,2,3,3,3]
Output: [1,2]
💡 Note: Element 1 appears once (unique), elements 2 and 3 appear multiple times (duplicates). So we have 1 unique element and 2 types of duplicate elements.
Example 2 — All Unique
$ Input: nums = [1,2,3,4,5]
Output: [5,0]
💡 Note: All elements appear exactly once, so we have 5 unique elements and 0 duplicate types.
Example 3 — All Same
$ Input: nums = [7,7,7,7]
Output: [0,1]
💡 Note: Element 7 appears 4 times (duplicate), so we have 0 unique elements and 1 type of duplicate element.

Constraints

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

Visualization

Tap to expand
Unique Elements CounterINPUTALGORITHMRESULT122333Array: [1,2,2,3,3,3]1Track with two sets2Unique → Duplicate3Count frequencies4Return both countsUnique Set: {1}Duplicate Set:{2, 3}[1, 2]1 unique element2 duplicate typesCounts returnedKey Insight:Using two sets allows us to track unique vs duplicate elements dynamically in a single pass,achieving O(n) time complexity by leveraging the O(1) lookup time of hash-based sets.TutorialsPoint - Unique Elements Counter | Single Pass Set Tracking
Asked in
Google 25 Amazon 20 Microsoft 15
28.5K Views
Medium Frequency
~15 min Avg. Time
842 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