Interview Prep #2 : HashSets and Intersection

 Interview Prep #2 : HashSets and Intersection

by Ashur Baroutta

    Continuing to explore different problems and tools to solve them, we follow up HashMaps with HashSets. A HashSet is simply a collection of unique objects, and because it only holds unique objects it allows us to add, remove, and check if an object is within the set in constant time. It differs from a HashMap in that it doesn't contain key-value pairs as by nature it cannot have more than 1 unique element, so an element essentially acts as its own key within a set. 

   HashSets allow us to use Intersection (set1.intersection(set2)) or (set1 & set2) (& being the intersect operator in python), allows us to pull shared elements from the sets.

    Our problem asks us "Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order." 

    We could use a loop and a HashMap (similar to finding duplicates but in reverse) to identify unique elements and then return a new list of those elements. However, we ought to work smarter not harder. Expanding the toolkit is essential for making problems like this simple! 

    So knowing sets can only have unique objects/elements within their collection, we can make the given arrays (num1 and num2) sets. This removes the duplicates immediately and after making the sets, we can use intersection and return the result as a list. What does this mean? 

    For example, if num1 = [1,2,2,1] when we make it a set the duplicates are removed and so its set would be {1,2}. Say our second array (num2) is [2,2], its set would be {2}. Great, how does this help? 
Well, our desired output is the point at which these 2 arrays intersect each other, in other words, what elements do they share? 

    Here is where the intersection makes a sentence out of a paragraph.  The code for our solution to the problem is as follows. 



    Understanding the data structure and its respective methods allowed me to beat out all but the top 5% of submissions ever submitted for the problem statement! I could have used loops and a HashMap or a variety of other ways to solve this problem, but I'm happy studying and applying my newfound knowledge led to a near-perfectly optimal runtime. 


    

Comments

  1. Congratulations!! It almost never works so smoothly. Enjoy the victory! 🎉

    ReplyDelete

Post a Comment

Popular posts from this blog

IP #6 : Reversing an Integer

IP#5 : LinkedList Removing Duplicates II