Python : Return the Intersection of Arrays

Опубликовано: 21 Март 2026
на канале: Grow with Data
54
5

Video 120: In this tutorial, we delve into the task of finding the intersection of two arrays.

We are given two sorted arrays of integers, a1 and a2, and are tasked with finding their intersection, i.e., the integers common to both arrays.

In this exercise, more than the result, we will discuss the time complexity of the code you are going to present.

Approach 1: General Looping Logic

In this approach, we iterate through one of the arrays and check if each element of that array is present in the other array. If present, we append those integers and return the result. However, the time complexity of this approach is O(n * m), where:

n: length of the first array
m: length of the second array
We iterate through the second array for each element in the first array. This approach is not scalable.

Approach 2: Sort and Compare Elements

In this approach, we sort the input arrays and use them for processing. The sorting algorithm can be like quicksort or mergesort, and the time complexity of sorting will be O(n log n + m log m). We then use a while loop to iterate through both sorted arrays simultaneously, comparing elements. In the worst case, where both arrays have distinct elements, this loop will execute for a number of iterations equal to the maximum of the lengths of a1 and a2. Hence, the loop contributes O(min(n, m)) to the time complexity. So, the overall time complexity of this process will be O(n log n + m log m + max(n, m)).

Since the input arrays are sorted and contain distinct elements, we can remove the sorting step. Hence, the time complexity will be reduced to O(min(n, m)).

For a comprehensive understanding and hands-on demonstration, be sure to watch the entire video. Happy coding!

code: https://github.com/jeganpillai/python...

Follow me on,
Website : https://growwithdata.co/
YouTube :    / @growwithdata  
TikTok :   / growwithdata  
LinkedIn :   / growwithdata  
Facebook :   / growwithdata.co  
twitter :   / growwithdata_co  
WhatsApp : https://whatsapp.com/channel/0029VaF8...
Instagram :   / growwithdata.co  


#recursive #countingalgorithm #list #looping #listmanipulation #uniquesubstring #longestsubstring #slicing #lineartimecomplexity #python #pythonquestions #pythontest #pythonprogramming #pythontutorial #python3 #pythonforbeginners #interviewquestions #interview #dataengineers #deinterview #pythoninterview #interviewquestions #leetcode #placementpreparation #meta #google #facebook #apple #netflix #amazon #google #faang #maanga #dataengineers #alphanumeric #nonalphanumeric #growwithdata #set #split #remove #pythonfunctions