Intersection of arrays arr1[] and arr2[]
To find intersection of 2 sorted arrays, follow the below approach :
- Use two index variables i and j, initial values i = 0, j = 0
- If arr1[i] is smaller than arr2[j] then increment i.
- If arr1[i] is greater than arr2[j] then increment j.
- If both are same then print any of them and increment both i and j.
Below is the implementation of the above approach
# Python program to find intersection of
# two sorted arrays
# Function prints Intersection of arr1[] and arr2[]
# m is the number of elements in arr1[]
# n is the number of elements in arr2[]
def
printIntersection(arr1, arr2, m, n):
i, j
=
0
,
0
while
i < m
and
j < n:
if
arr1[i] < arr2[j]:
i
+
=
1
elif
arr2[j] < arr1[i]:
j
+
=
1
else
:
print
(arr2[j])
j
+
=
1
i
+
=
1
# Driver program to test above function
arr1
=
[
1
,
2
,
4
,
5
,
6
]
arr2
=
[
2
,
3
,
5
,
7
]
m
=
len
(arr1)
n
=
len
(arr2)
printIntersection(arr1, arr2, m, n)
# This code is contributed by Pratik Chhajer
Output:
2 5
Time Complexity : O(m + n)
Handling duplicate in Arrays :
Above code does not handle duplicate elements in arrays. The intersection should not count duplicate elements. To handle duplicates just check whether current element is already present in intersection list. Below is the implementation of this approach.
- Python3
# Python3 program to find Intersection of two
# Sorted Arrays (Handling Duplicates)
def
IntersectionArray(a, b, n, m):
'''
:param a: given sorted array a
:param n: size of sorted array a
:param b: given sorted array b
:param m: size of sorted array b
:return: array of intersection of two array or -1
'''
Intersection
=
[]
i
=
j
=
0
while
i < n
and
j < m:
if
a[i]
=
=
b[j]:
# If duplicate already present in Intersection list
if
len
(Intersection) >
0
and
Intersection[
-
1
]
=
=
a[i]:
i
+
=
1
j
+
=
1
# If no duplicate is present in Intersection list
else
:
Intersection.append(a[i])
i
+
=
1
j
+
=
1
elif
a[i] < b[j]:
i
+
=
1
else
:
j
+
=
1
if
not
len
(Intersection):
return
[
-
1
]
return
Intersection
# Driver Code
if
__name__
=
=
"__main__"
:
arr1
=
[
1
,
2
,
2
,
3
,
4
]
arr2
=
[
2
,
2
,
4
,
6
,
7
,
8
]
l
=
IntersectionArray(arr1, arr2,
len
(arr1),
len
(arr2))
print
(
*
l)
Output:
2 4
Time Complexity : O(m + n)
Auxiliary Space : O(min(m, n))