Tutorialspoint
Problem
Solution
Submissions

Intersection of Two Arrays

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

Write a C 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 the result can be returned in any order.

An intersection of two arrays contains the elements that appear in both arrays.

Example 1
  • Input: nums1 = [1,2,2,1], nums2 = [2,2]
  • Output: [2]
  • Explanation: The element 2 appears in both arrays. The result should contain only unique elements, so [2] is returned.
Example 2
  • Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
  • Output: [4,9] or [9,4]
  • Explanation: Both 4 and 9 appear in both arrays. The result can be returned in any order.
Constraints
  • 1 ≤ nums1.length, nums2.length ≤ 1000
  • 0 ≤ nums1[i], nums2[i] ≤ 1000
  • Each array should be treated as a set (no duplicates in the output)
  • Time Complexity: O(n + m) where n and m are the lengths of the arrays
  • Space Complexity: O(min(n, m))
ArraysKPMGLTIMindtree
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 set to store the unique elements from the first array
  • Iterate through the second array, checking if each element exists in the hash set
  • If an element exists in the hash set, add it to the result set
  • Convert the result set to an array
  • For better performance, iterate through the smaller array to create the hash set

Steps to solve by this approach:

 Step 1: Create a hash set (implemented as an array) to track numbers in the first array.
 Step 2: Iterate through nums1 and mark each number's presence in the hash set.
 Step 3: Allocate memory for the result array.
 Step 4: Iterate through nums2 and check if each number exists in the hash set.
 Step 5: If a number exists in the hash set and hasn't been added to the result yet, add it to the result.
 Step 6: Mark the number as processed in the hash set to avoid duplicates.
 Step 7: Return the result array with its size.

Submitted Code :