In modern JavaScript, two powerful built-in data structures are Set
and Map
. They are often underutilized by beginners, but mastering them can lead to cleaner and more efficient code — especially when solving algorithmic problems like those on LeetCode.
Set
?A Set
is a collection of unique values. This means no duplicate elements are allowed. It’s perfect for when you want to keep track of a group of distinct items.
const mySet = new Set();mySet.add(1);mySet.add(2);mySet.add(2); // duplicate, will be ignoredconsole.log(mySet.has(2)); // trueconsole.log(mySet.size); // 2mySet.delete(1);mySet.clear(); // removes all elements
Map
?A Map
is a collection of key-value pairs, similar to an object, but with a few key differences:
const myMap = new Map();myMap.set('name', 'Alice');myMap.set(42, 'The answer');myMap.set(true, 'Yes');console.log(myMap.get(42)); // "The answer"console.log(myMap.has('name')); // truemyMap.delete(true);myMap.clear(); // removes everything
Given two integer arrays
nums1
andnums2
, return an array of their intersection. Each element in the result must be unique, and you may return the result in any order.
We need to find unique common elements. This screams: use Set
!
var intersection = function(nums1, nums2) {const set1 = new Set(nums1);const result = new Set();for (let num of nums2) {if (set1.has(num)) {result.add(num);}}return [...result]; // convert Set back to Array};
intersection([1, 2, 2, 1], [2, 2]); // Output: [2]intersection([4, 9, 5], [9, 4, 9, 8, 4]); // Output: [4, 9]
Set
vs Map
Use Case | Use Set | Use Map |
---|---|---|
Unique values only | ✅ Yes | 🚫 Not suitable |
Key-value pairs | 🚫 Not applicable | ✅ Yes |
Fast membership check | ✅ O(1) lookup | ✅ O(1) key lookup |
Store extra info per item | 🚫 No | ✅ Yes (value per key) |
Both Set
and Map
offer powerful capabilities that are often more efficient and expressive than arrays or plain objects, especially for algorithmic problems.
✅ Use Set
when you need uniqueness or fast existence checks.
✅ Use Map
when you need to associate values with keys (like a hash table).
💬 Now it’s your turn! Try using Set
and Map
in your next LeetCode challenge — you’ll be surprised how much cleaner your code becomes.
Quick Links
Legal Stuff
Social Media