Find the duplicate element in the given array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Find the duplicate element in the given array

Find the duplicate element in the given array. [1, 5, 2, 2, 3, 4, 3, 5, 2, 6, 7, 9, 8, 5] Output: 2 3 5 I've tried with this but it only worked for 2 duplicate values. If it's 3 or 4 duplicate values then it won't work. Can you help me, please? My Code: int arr[] = {2,3,4,2,5,3,7,8,9,2,4}; Arrays.sort(arr); for (int i = 0; i < arr.length; i++) { for (int j = i + 1; j < arr.length; j++) { if(arr[i] == arr[j]){ System.out.println(arr[i]); } } }

14th Oct 2022, 3:25 PM
Fuad Hassan
Fuad Hassan - avatar
1 Answer
+ 1
Task is to print only dublicate elements..!!? But What it means 3 or 4 dublicates? Your code prints dublicates values only but the same in number of dublicates-1 times.. First by outer loop, print element if you found a dublicate, then skip next same dublicate elements. So use a outer for loop for finding dublicate, if you find a dublicate then skip next elements by another loop innerly in if block like if( ar[i] == ar[i+1] ) { System.out.println(ar[i]) ; while( i<ar.length && ar[i] == ar[i+1] ) i++; } I am checked code but hope it helps to correct it...
14th Oct 2022, 4:20 PM
Jayakrishna 🇮🇳