Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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]
Advertisements