Hello Programers,

**Problem**:

How to find duplicate values in each row of 2D array. For example , we have 2d array as below:

[table id=5 /]

Output should be : 4 , Because 4 is common in each row.

### Solution:

This was really brainstorming as I want to avoid multiple for loops to solve this problem. My logic to solve above problem is as below:

- I assume all elements in first row are duplicate elements i.e. exists in all rows.
- I store all elements of first row in a HashSet say firstRow. I used HashSet just to add only unique elements as a row can have duplicate elements as well.
- Now I take all elements of second row and store them in a different HashSet say secondRow.
- Now I take intersection of firstRow and secondRow. It will return me only elements which are common in both rows.
- If size of firstRow is zero, we will stop further iteration as it means there is no element which is common in all rows.
- If size of firstRow is not zero, repeat step 4 for next row i.e. 3rd row.

### Understand logic in Pic:

**Java Programs:**

[java]

package Arrays;

import java.util.HashSet;

import java.util.Set;

public class DuplicateElementInRows {

public static void main(String[] args) {

// An input array

int arrayValues[][] = { { 4, 67, 34, 90 }, { 9, 4, 11, 100 }, { 6, 12, 9, 4 }, { 78, 87, 4, 2 } };

// A set to store expected duplicates

Set<Integer> expectedDuplicates = new HashSet<Integer>();

// To store next row elements

Set<Integer> deleteRow = new HashSet<Integer>();

boolean duplicates=true;

// Iteration starts from here

for (int i = 0; i < arrayValues.length; i++) {

// This will work for if every row has different number of elements

for (int j = 0; j < arrayValues[i].length; j++) {

// Assuming elements of first row are duplicates

if (i == 0)

expectedDuplicates.add(arrayValues[i][j]);

// If not first row, add in another HashSet

else {

deleteRow.add(arrayValues[i][j]);

}

}

// Intersection should be avoided for first row

if (i != 0) {

// Intersection of two sets

expectedDuplicates.retainAll(deleteRow);

// Emptying deleteRow

deleteRow.clear();

// Check if intersection makes expectedDuplicates size 0.

if (expectedDuplicates.size() == 0) {

duplicates=false;

break;

}

}

}

// Printing Duplicates

if(duplicates)

System.out.println("Duplicated elemets in all rows: "+expectedDuplicates);

else

System.out.println("There is no duplicate elements.");

}

}

[/java]

Output:

Hope it will be easy to understand for you guys. If not feel free to comment.

If you have any different way to solve above problem please comment. It will be learning for everyone.

If you like my posts, please like, comment, share and subscribe.

#HappyCoding