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 i such that nums1[i] exists in nums2
  • answer2: the number of indices i such that nums2[i] exists in nums1

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
Find Common Elements Between Two Arraysnums143231Index: 0 1 2 3 4nums223147Index: 0 1 2 3 4Count matching elementsanswer1 = 4Elements in nums1 that exist in nums2answer2 = 4Elements in nums2 that exist in nums1Result: [4, 4]
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
Asked in
Amazon 35 Google 28
25.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen