
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].
- The arrays [1, 2, 2, 1] and [2, 2] are compared element by element.
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.
- The arrays [4, 9, 5] and [9, 4, 9, 8, 4] are compared.
Constraints
- 1 ≤ arr1.length, arr2.length ≤ 1000
- 0 ≤ arr1[i], arr2[i] ≤ 1000
- Time Complexity: O(n + m)
- Space Complexity: O(min(n, m))
Editorial
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. |
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