44. Find Common Elements Between Two Arrays

EasyArrayArray

You are given two integer arrays nums1 and nums2. Return the number of elements in nums1 that also appear in nums2.

Note: Count each occurrence in nums1 separately — if 3 appears twice in nums1 and once in nums2, it contributes 2 to the count.

Input: Two integer arrays nums1 and nums2.

Output: Integer — count of elements in nums1 that also appear in nums2.

Examples

Example 1
Input: [2,3,2], [1,3]
Output: 1
Explanation: nums2 = {1,3}. Walk nums1 left to right: 2 is not in nums2, 3 is in nums2 (+1), 2 is not in nums2. Total = 1.
Example 2
Input: [3,4,2,3], [1,5]
Output: 0
Explanation: nums2 = {1,5}. None of 3, 4, 2, 3 appear in nums2. Total = 0.
Example 3
Input: [1,2,3], [1,2,3]
Output: 3
Explanation: Every element of nums1 appears in nums2. Total = 3.
Example 4
Input: [1,1,2,2,3], [1,2,3]
Output: 5
Explanation: Each occurrence in nums1 is counted separately: 1, 1, 2, 2, 3 all appear in nums2 = {1,2,3}. Total = 5.

Constraints

Asked by

BloombergGoogleMetaAmazon
Solve this problem in the editor →