Tutorialspoint
Problem
Solution
Submissions

Intersection of Two Arrays

Certification: Basic Level Accuracy: 66.67% Submissions: 12 Points: 5

Write a Java program to find the intersection of two arrays. Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and appear as many times as it shows in both arrays.

Example 1
  • Input: nums1 = [1,2,2,1], nums2 = [2,2]
  • Output: [2]
  • Explanation:
    • Element 2 appears in both arrays
Example 2
  • Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
  • Output: [4, 9]
  • Explanation:
    • Elements 4 and 9 are common to both arrays
Constraints
  • 1 ≤ nums1.length, nums2.length ≤ 1000
  • 0 ≤ nums1[i], nums2[i] ≤ 1000
  • Time Complexity: O(n + m)
  • Space Complexity: O(min(n, m))
ArraysFacebookTech Mahindra
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 HashSet to store unique elements from one array.
  • Iterate through the second array to find matching elements.
  • Use another HashSet to prevent duplicates in the result.
  • Convert the resulting set to an array for the final output.

Steps to solve by this approach:

 Step 1: Create a HashSet from the first array to store unique elements.
 Step 2: Create another HashSet to store the intersection elements.
 Step 3: Iterate through the second array and check if each element exists in the first HashSet.
 Step 4: If an element exists in both arrays, add it to the intersection HashSet.
 Step 5: Convert the intersection HashSet to an array.
 Step 6: Return the array containing the intersection elements.

Submitted Code :