The Find Common Elements Between Two Arrays coding problem asks you to compare two integer arrays, nums1 and nums2. You need to find two values:
nums1 such that nums1[i] exists in nums2.nums2 such that nums2[j] exists in nums1.
This is a basic set membership and counting task.This "Easy" problem is used by Meta and Amazon to evaluate basic data structure selection. it's a test of whether you recognize the Hash Table interview pattern. While nested loops would take , using a Set reduces the lookup time to , resulting in an solution. It evaluations your ability to optimize simple search operations.
This problem uses Hash Sets for membership testing.
nums1 into a set set1.nums2 into a set set2.nums1: if nums1[i] is in set2, increment count1.nums2: if nums2[j] is in set1, increment count2.[count1, count2].nums1 = [2, 3, 2], nums2 = [1, 2]
set1 = {2, 3}, set2 = {1, 2}.nums1:
set2. (Count1 = 1)set2.set2. (Count1 = 2)nums2:
set1.set1. (Count2 = 1)
Result: [2, 1].Set membership is the most common use case for a Hash Set. If you need to check "Is this element in that collection?" multiple times, always build a Set from the collection first.