Intersection of Two Arrays
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Return the values that appear in both lists, each listed once.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1Duplicates should not matter. Which structure forgets duplicates?
- Hint 2Check each value of one list against a set made from the other.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
You and a friend each have a contact list in your phone. Which people do you both know? You memorise your friend's list (as a set), then go through yours: anyone you recognise from your friend's list goes into the "common" list, once only.
- The obvious way
Compare every pair with nested loops: O(n x m).
- The key insight
Put one list into a set (lookup is one step). Walk through the other list; every value found in the set is common. Collect the answers in another set so each appears once.
- The algorithm
- Make a set from the first list.
- Walk through the second list.
- Each value that is in the set goes into the answer set.
- Return the answer as a list.
Watch it run
Examplefirst = [1, 2, 2, 1], second = [2, 2]
Make a set from the first list: duplicates vanish.
set: {1, 2}Where people slip
- If duplicates must be kept (Intersection II), count with a dictionary instead of using sets.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def intersection(nums1, nums2):
known = set(nums1) # everything the first list has
common = set()
for number in nums2:
if number in known:
common.add(number)
return list(common)
# equivalent: list(set(nums1) & set(nums2))Now close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.