Tutorialspoint
Problem
Solution
Submissions

Array Intersection

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a JavaScript program to find the intersection of two arrays. The intersection should contain elements that appear in both arrays. Each element in the result should appear as many times as it shows up in both arrays. Return the result as an array.

Example 1
  • Input: arr1 = [1, 2, 2, 1], arr2 = [2, 2]
  • Output: [2, 2]
  • Explanation:
    • The arrays [1, 2, 2, 1] and [2, 2] are compared element by element.
    • Element 2 appears twice in both arrays.
    • Therefore, the intersection contains [2, 2].
Example 2
  • Input: arr1 = [4, 9, 5], arr2 = [9, 4, 9, 8, 4]
  • Output: [4, 9]
  • Explanation:
    • The arrays [4, 9, 5] and [9, 4, 9, 8, 4] are compared.
    • Element 4 appears once in arr1 and twice in arr2, so it appears once in result.
    • Element 9 appears once in arr1 and twice in arr2, so it appears once in result.
    • Element 5 appears only in arr1, so it's not included.
Constraints
  • 1 ≤ arr1.length, arr2.length ≤ 1000
  • 0 ≤ arr1[i], arr2[i] ≤ 1000
  • Time Complexity: O(n + m)
  • Space Complexity: O(min(n, m))
ArraysCapgeminiZomato
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a hash map to count the frequency of elements in the first array
  • Iterate through the second array and check if elements exist in the hash map
  • If an element exists and its count is greater than 0, add it to the result
  • Decrease the count in the hash map after adding to the result
  • Return the result array containing common elements

Steps to solve by this approach:

 Step 1: Create a Map to store frequency count of elements in the first array
 Step 2: Iterate through the first array and populate the frequency map
 Step 3: Initialize an empty result array to store intersection elements
 Step 4: Iterate through the second array element by element
 Step 5: For each element, check if it exists in frequency map with count > 0
 Step 6: If exists, add to result array and decrement count in frequency map
 Step 7: Return the result array containing all common elements

Submitted Code :