Fundamentals/Sets - Uniqueness
← PrevNext →
Given an array of integers, return a list containing only the unique elements from the array. Each value should appear exactly once in the result, and the order of first appearance should be preserved.
Use a hash set to track which values have already been seen so that membership testing and insertion run in O(1) on average.
Input
arr: an array of integers (may contain duplicates)
Output
An array of the distinct values from arr, in the order they first appear.
Examples
Example 1
Inputarr = [1, 2, 3, 4, 5]
Output[1, 2, 3, 4, 5]
Explanation: All values are already unique, so the output mirrors the input.
Example 2
Inputarr = [3, 1, 4, 1, 5, 9]
Output[3, 1, 4, 5, 9]
Explanation: The second 1 is a duplicate of the first 1 and is omitted; every other value appears once in order of first appearance.
Example 3
Inputarr = [10, 20]
Output[10, 20]
Constraints
  • 0 <= arr.length
  • Order of first occurrence must be preserved.