- Related Questions & Answers
- Intersection of Two Arrays II in Python
- Intersection of two arrays in C#
- Intersection of two arrays in Java
- Intersection of Two Arrays in C++
- The intersection of two arrays in Python (Lambda expression and filter function )
- How to get the intersection of two arrays in MongoDB?
- How to find the intersection of two arrays in java?
- Intersection of Two Linked Lists in Python
- C++ program to find union and intersection of two unsorted arrays
- Intersection of Three Sorted Arrays in C++
- Python program to find Intersection of two lists?
- Intersection of two HashSets in C#
- Get the intersection of two sets in Java
- C# program to find Intersection of two lists
- Program for Point of Intersection of Two Lines in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have two arrays A and B, there are few elements in these array. We have to find the intersection of them. So if A = [1, 4, 5, 3, 6], and B = [2, 3, 5, 7, 9], then intersection will be [3, 5]

To solve this, we will follow these steps −

- Take two arrays A and B
- if length of A is smaller than length of B, then swap them
- calculate the frequency of elements in the array and store them into m
- for each element e in B, if e is present in m, and frequency is non-zero,
- decrease frequency m[e] by 1
- insert e into the resultant array

- return the resultant array

Let us see the following implementation to get better understanding −

class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ m = {} if len(nums1)<len(nums2): nums1,nums2 = nums2,nums1 for i in nums1: if i not in m: m[i] = 1 else: m[i]+=1 result = [] for i in nums2: if i in m and m[i]: m[i]-=1 result.append(i) return result ob1 = Solution() print(ob1.intersect([1,4,5,3,6], [2,3,5,7,9]))

[1,4,5,3,6] [2,3,5,7,9]

[3,5]

Advertisements