
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Intersection of Two Arrays II in Python
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
Example
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]))
Input
[1,4,5,3,6] [2,3,5,7,9]
Output
[3,5]
- Related Articles
- Intersection of two arrays in Java
- Intersection of two arrays in C#
- Intersection of Two Arrays in C++
- Intersection of two arrays JavaScript
- 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++
- Python - Intersection of two String
- How to find intersection between two Numpy arrays?
- Unique intersection of arrays in JavaScript
- Intersection of Two Linked Lists in Python
- How to Create an Array using Intersection of two Arrays in JavaScript?
- Golang program to find intersection of two sorted arrays using two pointer approach
- C program to perform intersection operation on two arrays

Advertisements