Find Common Elements in Two Arrays – Intersection of two Arrays

Write a c program to find common elements in two arrays. Given two positive integer arrays arr1 and arr2 of lengths len1 and len2 we have to write a c code to find intersection of these two arrays. Both the arrays are sorted.

Let’s assume we have following two sorted arrays arr1 and arr2.

int arr1[] = {2,  3,  4,  5,  6};
int arr2[] = {4,  6,  7,  8,  9};

So the common elements in these two arrays is 4 and 6.

Find Common Elements in Two Arrays

C Program to Find Common Elements in Two Arrays

First Method (Naive Approach) –   Find Common Elements in Two Arrays using Two For Loops

In this approach, we take each element of a first array and compare with each element of a second array.

The time complexity of this approach is O(mn), Where m and n are the number of elements in array1 and array2.

Subscribe Our Tutorials

Get Latest Updates on Facebook

C Program to Find Missing Number in Array

Java Program to Find Intersection of Two Arrays

Find Common Elements in Three Sorted Arrays

Second Method  – This approach is better than the first approach in terms of time complexity.

Implementation Logic:

i) Use two index variables i and j, Initialized them with 0.
ii) If arr1[i] is smaller than arr2[j] then increment i.
iii) If arr1[i] is greater than arr2[j] then increment j.
iv) If both are same then print any of the array value and increment both i and j.

Program to implement a stack using an array

The time complexity of this approach is O(m+n).


Program to search an element in an array

Programming questions on linked list


I have explained these two approaches for finding common elements in two arrays. If you know some other method please let us know through your comments.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , , . Bookmark the permalink.