Solve LeetCode 349. Intersection of Two Arrays using an optimal Set-based approach in JavaScript 🚀
🔗 Problem Link:
https://leetcode.com/problems/interse...
🧠 Approach (Set / Hashing)
In this problem, we need to find the unique common elements between two arrays.
✅ We use Set because:
It removes duplicates automatically
Provides O(1) lookup time
💡 Steps:
Convert nums1 into a Set
Convert nums2 into a Set (to ensure uniqueness)
Loop through one set and check if elements exist in the other
Return the result
💻 Code (JavaScript)
var intersection = function(nums1, nums2) {
let set1 = new Set(nums1)
let set2 = new Set(nums2)
let arr = [...set2]
let result = arr.filter(num = set1.has(num))
return result
};
⚡ Complexity
Time Complexity: O(n + m)
Space Complexity: O(n + m)
📢 Call to Action
If you found this helpful ❤️
👍 Like the video
💬 Comment your doubts or approach
🔔 Subscribe for daily LeetCode solutions
Keep coding and keep improving 💻🔥
🏷️ Tags
#leetcode #leetcode349 #intersectionofarrays #javascriptcoding #dsa #datastructures #algorithms #codinginterview #webdevelopment #programming #codingpractice #setinjavascript #hashing #leetcodeeasy