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: [5,4]
💡 Note: For nums1: all elements 4,3,2,3,1 exist in nums2, so answer1=5. 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 Arrays INPUT nums1 (n=5): 4 3 2 3 1 i=0 i=1 i=2 i=3 i=4 nums2 (m=5): 2 3 1 4 7 i=0 i=1 i=2 i=3 i=4 Goal: answer1: Count nums1[i] that exist in nums2 answer2: Count nums2[i] that exist in nums1 ALGORITHM STEPS 1 Create Hash Sets set1 = {4,3,2,1} set2 = {2,3,1,4,7} 2 Count answer1 For each nums1[i], check if in set2 3 Count answer2 For each nums2[i], check if in set1 4 Return Result [answer1, answer2] O(1) Lookup 4 in set2? YES 3 in set2? YES 2 in set2? YES 3 in set2? YES 1 in set2? YES Count: 4 FINAL RESULT answer1 Matches: 4 3 2 3 1 All 4 unique values found! = 4 answer2 Matches: 2 3 1 4 7 7 not in set1 (X) = 4 Output: [4, 4] OK - Verified! Key Insight: Using Hash Sets converts O(n*m) brute force to O(n+m) time complexity. Set creation is O(n) and O(m), lookups are O(1). Count indices, not unique values! Space Complexity: O(n + m) for storing both sets TutorialsPoint - Find Common Elements Between Two Arrays | Hash Set Optimization
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