- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- 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]

- Related Questions & Answers
- Intersection of two arrays JavaScript
- Intersection of two arrays in C#
- Intersection of two arrays in Java
- Intersection of Two Arrays in C++
- Python - Intersection of two String
- The intersection of two arrays in Python (Lambda expression and filter function )
- How to find the intersection of two arrays in java?
- How to get the intersection of two arrays in MongoDB?
- Find Union and Intersection of two unsorted arrays in C++
- Intersection of Two Linked Lists in Python
- How to find intersection between two Numpy arrays?
- Unique intersection of arrays in JavaScript
- C++ program to find union and intersection of two unsorted arrays
- C program to perform intersection operation on two arrays
- Finding intersection of multiple arrays - JavaScript

Advertisements