Intersection of Two Sorted Arrays
In this lesson, you will learn how to find the intersection of two sorted arrays in Python.
We'll cover the following...
In this lesson, we will be solving the following problem:
Given two sorted arrays, A
and B
, determine their intersection. What elements are common to A
and B
?
There is a one-line solution to this problem in Python that will also work in the event when the arrays are not sorted.
Press + to interact
A = [2, 3, 3, 5, 7, 11]B = [3, 3, 7, 15, 31]print(set(A).intersection(B))
The set
function in Python operates on a list and returns a set object that contains the unique elements of that list. A
is converted into a set on line 4 by using set(A)
. Now there is another built-in function in Python called intersection
which operates on sets. In the code above, intersection
returns a set which is the intersection of A
...