LeetCode 349: Intersection of Two Arrays - Interview Prep Ep 49

preview_player
Показать описание


⭐ Support my channel and connect with me:

Solutions explained:

Solution 1. We could use two hash sets, one for each array, then do intersection on both sets;
Slight modification: use the second set to hold all intersection elements rather than all distinct elements in the second array;
Solution 2. We can sort one of the two arrays, then use binary search to find intersection elements;
Solution 3. We can sort both arrays, then use two pointers to iterate through both of the sorted arrays.

// TOOLS THAT I USE:

// MY FAVORITE BOOKS:

My ENTIRE Programming Equipment and Computer Science Bookshelf:

And make sure you subscribe to my channel!

Your comments/thoughts/questions/advice will be greatly appreciated!

#softwareengineering #leetcode #algorithms #coding #interview #SDE #SWE #SiliconValley #programming #datastructures
Рекомендации по теме
Комментарии
Автор

thanks a lot, Sir. Your way of teaching is outstanding.

Blissfulvibes
Автор

Thank you. All three are very clear and helpful.

Chloe-sihq
Автор

I was assuming we should turn the subarray occuring in each of the vectors, so I wrote code that works for all cases but I got a seg-fault even though in my linux system, it passes all of the cases. Probably some cases don't pass in leetcode. Anyways, then I realized the order of the numbers are not considered in this question, just a set is enough to check for the occurences.

followthewhiterabbit
Автор

This is interesting, it is even more interesting LeetCode accepts your last answer. Here is why, you sort the two arrays at the beginning then compare what occurs at each index to see if they are the same. Does it work for the following array examples?

{1, 2, 3, 4} and {4, 5, 6, 7} These are pre sorted. So when your code goes to collect the numbers that are the same it wont know that it saw 4 in one set vs the other. Here is an example from wikipedia

{1, 2, 3} and {2, 3, 4} = {2, 3}
But your code says no intersect.

pashapa
Автор

how is the time complexity of the 3rd approach O(nlogn) I thought it would be O(n)

insane