Unique Values with Set<number>
Write a TypeScript function that takes an array of numbers and returns a new array containing only unique values using Set
TypeScript's generic syntax Set
Converting a Set back to an array uses the spread operator [...set] or Array.from(set). TypeScript infers the resulting array type as number[] from the Set
Time complexity is O(n) where n is the input length. Set operations are O(1) average for add and has. Space complexity is O(k) where k is the number of unique elements.
Edge cases include empty arrays, arrays with all duplicates, arrays with all unique values, and ensuring the function returns a new array without modifying the input.
Example Input & Output
With negatives
Empty array
Already unique
Removes duplicates
All same values
Algorithm Flow

Solution Approach
Best Answers
function solution(nums: number[]): number[] {
var seen: any = {};
var res: number[] = [];
for (var i = 0; i < nums.length; i++) {
if (!seen[nums[i]]) { seen[nums[i]] = true; res.push(nums[i]); }
}
return res;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
