Find Common Elements Between Two Arrays - Problem
You are given two integer arrays nums1 and nums2 of sizes n and m, respectively.
Your task is to find how many elements from each array exist in the other array. More specifically:
- answer1: Count how many indices
iexist such thatnums1[i]can be found somewhere innums2 - answer2: Count how many indices
iexist such thatnums2[i]can be found somewhere innums1
Return the results as [answer1, answer2].
Note: We're counting indices, not unique elements. If an element appears multiple times in an array, each occurrence is counted separately if it exists in the other array.
Example: If nums1 = [4,3,2,3,1] and nums2 = [2,2,5,2,3,6], then:
- Elements 4, 3, 2, 3 from nums1 exist in nums2 (4 elements)
- Elements 2, 2, 2, 3 from nums2 exist in nums1 (4 elements)
- Return
[4, 4]
Input & Output
example_1.py โ Basic Case
$
Input:
nums1 = [4,3,2,3,1], nums2 = [2,2,5,2,3,6]
โบ
Output:
[3,4]
๐ก Note:
From nums1: elements 3,2,3 exist in nums2 (3 count). From nums2: elements 2,2,2,3 exist in nums1 (4 count).
example_2.py โ No Common Elements
$
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.
example_3.py โ All Elements Match
$
Input:
nums1 = [2,3,2], nums2 = [3,2]
โบ
Output:
[3,2]
๐ก Note:
All elements from nums1 (2,3,2) exist in nums2. All elements from nums2 (3,2) exist in nums1.
Constraints
- 1 โค nums1.length, nums2.length โค 1000
- 1 โค nums1[i], nums2[i] โค 100
- Arrays can contain duplicate elements
- Count each index occurrence, not unique values
Visualization
Tap to expand
Understanding the Visualization
1
Build Directory
Create a quick-lookup directory (hash set) of students in one section
2
Count Matches
Go through the other section and count how many are in your directory
3
Reverse Process
Repeat the process in the opposite direction
4
Get Results
Return the counts from both directions
Key Takeaway
๐ฏ Key Insight: Using hash sets transforms O(nยฒ) nested loops into O(n+m) linear time by replacing repeated linear searches with constant-time lookups, like having a student directory instead of scanning enrollment lists repeatedly.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code