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
<?php
// PHP 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[] */
function
printIntersection(
$arr1
,
$arr2
,
$m
,
$n
)
{
$i
= 0 ;
$j
= 0;
while
(
$i
<
$m
&&
$j
<
$n
)
{
if
(
$arr1
[
$i
] <
$arr2
[
$j
])
$i
++;
else
if
(
$arr2
[
$j
] <
$arr1
[
$i
])
$j
++;
/* if arr1[i] == arr2[j] */
else
{
echo
$arr2
[
$j
],
" "
;
$i
++;
$j
++;
}
}
}
// Driver Code
$arr1
=
array
(1, 2, 4, 5, 6);
$arr2
=
array
(2, 3, 5, 7);
$m
=
count
(
$arr1
);
$n
=
count
(
$arr2
);
// Function calling
printIntersection(
$arr1
,
$arr2
,
$m
,
$n
);
?>
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))