Find duplicates in a given array when elements are not limited to a range | Java implementation of the above approach ; Function to find the Duplicates , if duplicate occurs 2 times or more than 2 times in array so , it will print duplicate value only once at output ; initialize ifPresent as false ; ArrayList to store the output ; checking if element is present in the ArrayList or not if present then break ; if element is not present in the ArrayList then add it to ArrayList and make ifPresent at true ; if duplicates is present then print ArrayList ; Driver Code
import java . util . ArrayList ; public class GFG { static void findDuplicates ( int arr [ ] , int len ) { boolean ifPresent = false ; ArrayList < Integer > al = new ArrayList < Integer > ( ) ; for ( int i = 0 ; i < len - 1 ; i ++ ) { for ( int j = i + 1 ; j < len ; j ++ ) { if ( arr [ i ] == arr [ j ] ) { if ( al . contains ( arr [ i ] ) ) { break ; } else { al . add ( arr [ i ] ) ; ifPresent = true ; } } } } if ( ifPresent == true ) { System . out . print ( al + " ▁ " ) ; } else { System . out . print ( " No ▁ duplicates ▁ present ▁ in ▁ arrays " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 11 , 40 , 12 , 5 , 6 , 5 , 12 , 11 } ; int n = arr . length ; findDuplicates ( arr , n ) ; } }