Find Common Elements in Three Sorted Arrays – Java Code

Write a java program to find common elements in three sorted arrays.

Given three sorted arrays, write a code to print intersection of three sorted arrays.

For example –

arr1 = {1, 5, 10, 20, 40, 80};
arr2 = {6, 7, 20, 80, 100};
arr3 = {3, 4, 15, 20, 30, 70, 80, 120};

Output : {20, 80}

20 and 80 are the common elements in 3 arrays. These two elements are the intersection of 3 sorted arrays.

Find common elements in three sorted arrays

Find common elements in three sorted arrays

We have discussed the problem statement.  Before jumping into the solution, let’s think what all approaches we can use to solve this problem. This problem is the extension of find intersection of two sorted arrays.

We will start with the easiest approach and then we will improve our solution to solve this problem efficiently.

Programming Video Tutorials

Find common elements in three sorted arrays video tutorial

Method 1: Beginner’s Approach

The simplest approach is to use three for loops to find intersection of three sorted arrays.

The time complexity of this approach is O(n^3).

 Find Common Elements in Three Sorted Arrays – Java Code

In our previous approach, we have solved this problem using three for loops. Let’s improve our solution and solve this problem in a single traversal.

The idea here is to traverse all the arrays simultaneously, and if we found common element just print it.

i) Declare three variables (x, y, z) and Initialized with zero.

ii) Run a while loop until the array lengths ( arr1.length > x, arr2.length > y, arr3.length > z) are greater than the declared variables.

iii) At each step compare the values to find the common element (arr1[x] == arr2[y] && arr2[y] == arr3[z]). If it’s found increment the value of all the three variables.

Else increment y if arr1[x] > arr2[y]. Increment z if arr2[y] > arr3[z], else increment x

The time complexity of this approach is O(N1 + N2 + N3).

Find sum of digits of a number

In this video tutorial, I have explained both the approaches using java code.

Find common elements in three sorted arrays video tutorial

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.