Find Common Elements Between Two Arrays - Problem
You are given two integer arrays nums1 and nums2 of sizes n and m, respectively.
Calculate the following values:
- answer1: the number of indices
isuch thatnums1[i]exists innums2 - answer2: the number of indices
isuch thatnums2[i]exists innums1
Return [answer1, answer2].
Input & Output
Example 1 — Basic Case
$
Input:
nums1 = [4,3,2,3,1], nums2 = [2,3,1,4,7]
›
Output:
[4,4]
💡 Note:
For nums1: all elements 4,3,2,3,1 exist in nums2, so answer1=4. For nums2: elements 2,3,1,4 exist in nums1 (7 doesn't), so answer2=4.
Example 2 — Partial Matches
$
Input:
nums1 = [3,4,2,3], nums2 = [1,5]
›
Output:
[0,0]
💡 Note:
No elements from nums1 exist in nums2, and no elements from nums2 exist in nums1, so both counts are 0.
Example 3 — All Different Sizes
$
Input:
nums1 = [2,4,6,8], nums2 = [1,2,3,4,5]
›
Output:
[2,2]
💡 Note:
From nums1: elements 2,4 exist in nums2 (answer1=2). From nums2: elements 2,4 exist in nums1 (answer2=2).
Constraints
- 1 ≤ nums1.length, nums2.length ≤ 1000
- 1 ≤ nums1[i], nums2[i] ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Input Arrays
Two integer arrays nums1 and nums2 with potentially overlapping elements
2
Count Common Elements
Count how many elements from nums1 exist in nums2, and vice versa
3
Return Counts
Return [answer1, answer2] representing both counts
Key Takeaway
🎯 Key Insight: Use hash sets to transform slow O(n) searches into fast O(1) lookups for efficient element comparison
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code