codeparrot/xlcost-text-to-code huggingface dataset:
Number of anomalies in an array |  ; Sort the array so that we can apply binary search . ; One by one check every element if it is anomaly or not using binary search . ; If arr [ i ] is not largest element and element just greater than it is within k , then return false . ; If there are more than one occurrences of arr [ i ] , return false . ; If arr [ i ] is not smallest element and just smaller element is not k distance away ; Driver Code
import java . util . * ; class GFG { static int countAnomalies ( int a [ ] , int n , int k ) { Arrays . sort ( a ) ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int u = upper_bound ( a , 0 , n , a [ i ] ) ; if ( u < n && a [ u ] - a [ i ] <= k ) continue ; int s = lower_bound ( a , 0 , n , a [ i ] ) ; if ( u - s > 1 ) continue ; if ( s > 0 && a [ s - 1 ] - a [ i ] <= k ) continue ; res ++ ; } return res ; } static int lower_bound ( int [ ] a , int low , int high , int element ) { while ( low < high ) { int middle = low + ( high - low ) / 2 ; if ( element > a [ middle ] ) low = middle + 1 ; else high = middle ; } return low ; } static int upper_bound ( int [ ] a , int low , int high , int element ) { while ( low < high ) { int middle = low + ( high - low ) / 2 ; if ( a [ middle ] > element ) high = middle ; else low = middle + 1 ; } return low ; } public static void main ( String [ ] args ) { int arr [ ] = { 7 , 1 , 8 } , k = 5 ; int n = arr . length ; System . out . print ( countAnomalies ( arr , n , k ) ) ; } }
Subarrays with distinct elements | Java program to calculate sum of lengths of subarrays of distinct elements . ; Returns sum of lengths of all subarrays with distinct elements . ; For maintaining distinct elements . ; Initialize ending point and result ; Fix starting point ; Calculating and adding all possible length subarrays in arr [ i . . j ] ; Remove arr [ i ] as we pick new stating point from next ; Driver Code
import java . util . * ; class geeks { public static int sumoflength ( int [ ] arr , int n ) { Set < Integer > s = new HashSet < > ( ) ; int j = 0 , ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { while ( j < n && ! s . contains ( arr [ j ] ) ) { s . add ( arr [ i ] ) ; j ++ ; } ans += ( ( j - i ) * ( j - i + 1 ) ) / 2 ; s . remove ( arr [ i ] ) ; } return ans ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 } ; int n = arr . length ; System . out . println ( sumoflength ( arr , n ) ) ; } }
Count subarrays having total distinct elements same as original array | Java program Count total number of sub - arrays having total distinct elements same as that original array . ; Method to calculate distinct sub - array ; Count distinct elements in whole array ; Reset the container by removing all elements ; Use sliding window concept to find count of subarrays having k distinct elements . ; If window size equals to array distinct element size , then update answer ; Decrease the frequency of previous element for next sliding window ; If frequency is zero then decrease the window size ; Driver method
import java . util . HashMap ; class Test { static int countDistictSubarray ( int arr [ ] , int n ) { HashMap < Integer , Integer > vis = new HashMap < Integer , Integer > ( ) { @ Override public Integer get ( Object key ) { if ( ! containsKey ( key ) ) return 0 ; return super . get ( key ) ; } } ; for ( int i = 0 ; i < n ; ++ i ) vis . put ( arr [ i ] , 1 ) ; int k = vis . size ( ) ; vis . clear ( ) ; int ans = 0 , right = 0 , window = 0 ; for ( int left = 0 ; left < n ; ++ left ) { while ( right < n && window < k ) { vis . put ( arr [ right ] , vis . get ( arr [ right ] ) + 1 ) ; if ( vis . get ( arr [ right ] ) == 1 ) ++ window ; ++ right ; } if ( window == k ) ans += ( n - right + 1 ) ; vis . put ( arr [ left ] , vis . get ( arr [ left ] ) - 1 ) ; if ( vis . get ( arr [ left ] ) == 0 ) -- window ; } return ans ; } public static void main ( String args [ ] ) { int arr [ ] = { 2 , 1 , 3 , 2 , 3 } ; System . out . println ( countDistictSubarray ( arr , arr . length ) ) ; } }
Count subarrays with same even and odd elements | Java program to find total number of even - odd subarrays present in given array ; function that returns the count of subarrays that contain equal number of odd as well as even numbers ; initialize difference and answer with 0 ; initialize these auxiliary arrays with 0 ; since the difference is initially 0 , we have to initialize hash_positive [ 0 ] with 1 ; for loop to iterate through whole array ( zero - based indexing is used ) ; incrementing or decrementing difference based on arr [ i ] being even or odd , check if arr [ i ] is odd ; adding hash value of ' difference ' to our answer as all the previous occurrences of the same difference value will make even - odd subarray ending at index ' i ' . After that , we will increment hash array for that ' difference ' value for its occurrence at index ' i ' . if difference is negative then use hash_negative ; else use hash_positive ; return total number of even - odd subarrays ; Driver code ; Printing total number of even - odd subarrays
class GFG { static int countSubarrays ( int [ ] arr , int n ) { int difference = 0 ; int ans = 0 ; int [ ] hash_positive = new int [ n + 1 ] ; int [ ] hash_negative = new int [ n + 1 ] ; hash_positive [ 0 ] = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] & 1 ) == 1 ) { difference ++ ; } else { difference -- ; } if ( difference < 0 ) { ans += hash_negative [ - difference ] ; hash_negative [ - difference ] ++ ; } else { ans += hash_positive [ difference ] ; hash_positive [ difference ] ++ ; } } return ans ; } public static void main ( String [ ] args ) { int [ ] arr = new int [ ] { 3 , 4 , 6 , 8 , 1 , 10 , 5 , 7 } ; int n = arr . length ; System . out . println ( " Total ▁ Number ▁ of ▁ Even - Odd " + " ▁ subarrays ▁ are ▁ " + countSubarrays ( arr , n ) ) ; } }
Given a binary tree , print out all of its root | A binary tree node has data , pointer to left child and a pointer to right child ; Given a binary tree , print out all of its root - to - leaf paths , one per line . Uses a recursive helper to do the work . ; Recursive helper function -- given a node , and an array containing the path from the root node up to but not including this node , print out all the root - leaf paths . ; append this node to the path array ; it 's a leaf, so print the path that led to here  ; otherwise try both subtrees ; Utility that prints out an array on a line ; Driver program to test all above functions ; Print all root - to - leaf paths of the input tree
class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; void printPaths ( Node node ) { int path [ ] = new int [ 1000 ] ; printPathsRecur ( node , path , 0 ) ; } void printPathsRecur ( Node node , int path [ ] , int pathLen ) { if ( node == null ) return ; path [ pathLen ] = node . data ; pathLen ++ ; if ( node . left == null && node . right == null ) printArray ( path , pathLen ) ; else { printPathsRecur ( node . left , path , pathLen ) ; printPathsRecur ( node . right , path , pathLen ) ; } } void printArray ( int ints [ ] , int len ) { int i ; for ( i = 0 ; i < len ; i ++ ) System . out . print ( ints [ i ] + " ▁ " ) ; System . out . println ( " " ) ; } public static void main ( String [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 1 ) ; tree . root . left = new Node ( 2 ) ; tree . root . right = new Node ( 3 ) ; tree . root . left . left = new Node ( 4 ) ; tree . root . left . right = new Node ( 5 ) ; tree . printPaths ( tree . root ) ; } }
Saddleback Search Algorithm in a 2D array | Java program to search an element in row - wise and column - wise sorted matrix ; Searches the element x in mat [ m ] [ n ] . If the element is found , then prints its position and returns true , otherwise prints " not ▁ found " and returns false ; set indexes for bottom left element ; if mat [ i ] [ j ] < x ; Driver Code
class GFG { static final int MAX = 100 ; static boolean search ( int mat [ ] [ ] , int m , int n , int x ) { int i = m - 1 , j = 0 ; while ( i >= 0 && j < n ) { if ( mat [ i ] [ j ] == x ) return true ; if ( mat [ i ] [ j ] > x ) i -- ; else j ++ ; } return false ; } public static void main ( String args [ ] ) { int mat [ ] [ ] = { { 10 , 20 , 30 , 40 } , { 15 , 25 , 35 , 45 } , { 27 , 29 , 37 , 48 } , { 32 , 33 , 39 , 50 } , { 50 , 60 , 70 , 80 } } ; if ( search ( mat , 5 , 4 , 29 ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }
Minimum number of distinct elements after removing m items | Java program for Minimum number of distinct elements after removing m items ; Function to find distintc id 's ; Store the occurrence of ids ; Start removing elements from the beginning ; Remove if current value is less than or equal to mi ; Return the remaining size ; Driver method to test above function
import java . util . HashMap ; import java . util . Map ; import java . util . Map . Entry ; public class DistinctIds { static int distinctIds ( int arr [ ] , int n , int mi ) { Map < Integer , Integer > m = new HashMap < Integer , Integer > ( ) ; int count = 0 ; int size = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( m . containsKey ( arr [ i ] ) == false ) { m . put ( arr [ i ] , 1 ) ; size ++ ; } else m . put ( arr [ i ] , m . get ( arr [ i ] ) + 1 ) ; } for ( Entry < Integer , Integer > mp : m . entrySet ( ) ) { if ( mp . getKey ( ) <= mi ) { mi -= mp . getKey ( ) ; count ++ ; } else return size - count ; } return size - count ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 1 , 2 , 3 , 3 } ; int m = 3 ; System . out . println ( distinctIds ( arr , arr . length , m ) ) ; } }
Number of Larger Elements on right side in a string | Java program to find counts of right greater characters for every character . ; Driver code
class GFG { static void printGreaterCount ( String str ) { int len = str . length ( ) , right [ ] = new int [ len ] ; for ( int i = 0 ; i < len ; i ++ ) { for ( int j = i + 1 ; j < len ; j ++ ) { if ( str . charAt ( i ) < str . charAt ( j ) ) { right [ i ] ++ ; } } } for ( int i = 0 ; i < len ; i ++ ) { System . out . print ( right [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { String str = " abcd " ; printGreaterCount ( str ) ; } }
Maximum consecutive numbers present in an array | Java program to find largest consecutive numbers present in arr [ ] . ; We insert all the array elements into unordered set . ; check each possible sequence from the start then update optimal length ; if current element is the starting element of a sequence ; Then check for next elements in the sequence ; increment the value of array element and repeat search in the set ; Update optimal length if this length is more . To get the length as it is incremented one by one ; Driver code
import java . util . * ; class GFG { static int findLongestConseqSubseq ( int arr [ ] , int n ) { HashSet < Integer > S = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) S . add ( arr [ i ] ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( S . contains ( arr [ i ] ) ) { int j = arr [ i ] ; while ( S . contains ( j ) ) j ++ ; ans = Math . max ( ans , j - arr [ i ] ) ; } } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 94 , 93 , 1000 , 5 , 92 , 78 } ; int n = arr . length ; System . out . println ( findLongestConseqSubseq ( arr , n ) ) ; } }
N / 3 repeated number in an array with O ( 1 ) space | Java program to find if any element appears more than n / 3. ; take the integers as the maximum value of integer hoping the integer would not be present in the array ; if this element is previously seen , increment count1 . ; if this element is previously seen , increment count2 . ; if current element is different from both the previously seen variables , decrement both the counts . ; Again traverse the array and find the actual counts . ; Driver code
class GFG { static int appearsNBy3 ( int arr [ ] , int n ) { int count1 = 0 , count2 = 0 ; int first = Integer . MIN_VALUE ; ; int second = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { if ( first == arr [ i ] ) count1 ++ ; else if ( second == arr [ i ] ) count2 ++ ; else if ( count1 == 0 ) { count1 ++ ; first = arr [ i ] ; } else if ( count2 == 0 ) { count2 ++ ; second = arr [ i ] ; } else { count1 -- ; count2 -- ; } } count1 = 0 ; count2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == first ) count1 ++ ; else if ( arr [ i ] == second ) count2 ++ ; } if ( count1 > n / 3 ) return first ; if ( count2 > n / 3 ) return second ; return - 1 ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 3 , 1 , 1 } ; int n = arr . length ; System . out . println ( appearsNBy3 ( arr , n ) ) ; } }
Count pairs in array whose sum is divisible by 4 | Java program to count pairs whose sum divisible by '4' ; Program to count pairs whose sum divisible by '4' ; Create a frequency array to count occurrences of all remainders when divided by 4 ; Count occurrences of all remainders ; If both pairs are divisible by '4' ; If both pairs are 2 modulo 4 ; If one of them is equal to 1 modulo 4 and the other is equal to 3 modulo 4 ; Driver code
import java . util . * ; class Count { public static int count4Divisibiles ( int arr [ ] , int n ) { int freq [ ] = { 0 , 0 , 0 , 0 } ; int i = 0 ; int ans ; for ( i = 0 ; i < n ; i ++ ) ++ freq [ arr [ i ] % 4 ] ; ans = freq [ 0 ] * ( freq [ 0 ] - 1 ) / 2 ; ans += freq [ 2 ] * ( freq [ 2 ] - 1 ) / 2 ; ans += freq [ 1 ] * freq [ 3 ] ; return ( ans ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 2 , 1 , 7 , 5 } ; int n = 5 ; System . out . print ( count4Divisibiles ( arr , n ) ) ; } }
Find Sum of all unique sub | Java for finding sum of all unique subarray sum ; Function for finding grandSum ; Calculate cumulative sum of array cArray [ 0 ] will store sum of zero elements ; Store all subarray sum in vector ; Sort the vector ; Mark all duplicate sub - array sum to zero ; Calculate total sum ; Return totalSum ; Driver Code
import java . util . * ; class GFG { static int findSubarraySum ( int arr [ ] , int n ) { int i , j ; int cArray [ ] = new int [ n + 1 ] ; for ( i = 0 ; i < n ; i ++ ) cArray [ i + 1 ] = cArray [ i ] + arr [ i ] ; Vector < Integer > subArrSum = new Vector < Integer > ( ) ; for ( i = 1 ; i <= n ; i ++ ) for ( j = i ; j <= n ; j ++ ) subArrSum . add ( cArray [ j ] - cArray [ i - 1 ] ) ; Collections . sort ( subArrSum ) ; int totalSum = 0 ; for ( i = 0 ; i < subArrSum . size ( ) - 1 ; i ++ ) { if ( subArrSum . get ( i ) == subArrSum . get ( i + 1 ) ) { j = i + 1 ; while ( subArrSum . get ( j ) == subArrSum . get ( i ) && j < subArrSum . size ( ) ) { subArrSum . set ( j , 0 ) ; j ++ ; } subArrSum . set ( i , 0 ) ; } } for ( i = 0 ; i < subArrSum . size ( ) ; i ++ ) totalSum += subArrSum . get ( i ) ; return totalSum ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 3 , 1 , 4 } ; int n = arr . length ; System . out . print ( findSubarraySum ( arr , n ) ) ; } }
Smallest number whose set bits are maximum in a given range | Java program to find number whose set bits are maximum among ' l ' and ' r ' ; Returns smallest number whose set bits are maximum in given range . ; Initialize the maximum count and final answer as ' num ' ; Traverse for every bit of ' i ' number ; If count is greater than previous calculated max_count , update it ; Driver code
class gfg { static int countMaxSetBits ( int left , int right ) { int max_count = - 1 , num = 0 ; for ( int i = left ; i <= right ; ++ i ) { int temp = i , cnt = 0 ; while ( temp > 0 ) { if ( temp % 2 == 1 ) ++ cnt ; temp >>= 1 ; } if ( cnt > max_count ) { max_count = cnt ; num = i ; } } return num ; } public static void main ( String [ ] args ) { int l = 1 , r = 5 ; System . out . println ( countMaxSetBits ( l , r ) ) ; l = 1 ; r = 10 ; System . out . print ( countMaxSetBits ( l , r ) ) ; } }
Find Sum of all unique sub | Java for finding sum of all unique subarray sum ; function for finding grandSum ; Go through all subarrays , compute sums and count occurrences of sums . ; Print all those sums that appear once . ; Driver code
import java . util . * ; class GFG { static int findSubarraySum ( int [ ] arr , int n ) { int res = 0 ; HashMap < Integer , Integer > m = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; for ( int j = i ; j < n ; j ++ ) { sum += arr [ j ] ; if ( m . containsKey ( sum ) ) { m . put ( sum , m . get ( sum ) + 1 ) ; } else { m . put ( sum , 1 ) ; } } } for ( Map . Entry < Integer , Integer > x : m . entrySet ( ) ) if ( x . getValue ( ) == 1 ) res += x . getKey ( ) ; return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 3 , 1 , 4 } ; int n = arr . length ; System . out . println ( findSubarraySum ( arr , n ) ) ; } }
Quickselect Algorithm | Java program of Quick Select ; partition function similar to quick sort Considers last element as pivot and adds elements with less value to the left and high value to the right and also changes the pivot position to its respective position in the final array . ; inserting elements of less value to the left of the pivot location ; swapping pivot to the final pivot location ; finds the kth position ( of the sorted array ) in a given unsorted array i . e this function can be used to find both kth largest and kth smallest element in the array . ASSUMPTION : all elements in arr [ ] are distinct ; find the partition ; if partition value is equal to the kth position , return value at k . ; if partition value is less than kth position , search right side of the array . ; if partition value is more than kth position , search left side of the array . ; Driver Code
import java . util . Arrays ; class GFG { public static int partition ( int [ ] arr , int low , int high ) { int pivot = arr [ high ] , pivotloc = low ; for ( int i = low ; i <= high ; i ++ ) { if ( arr [ i ] < pivot ) { int temp = arr [ i ] ; arr [ i ] = arr [ pivotloc ] ; arr [ pivotloc ] = temp ; pivotloc ++ ; } } int temp = arr [ high ] ; arr [ high ] = arr [ pivotloc ] ; arr [ pivotloc ] = temp ; return pivotloc ; } public static int kthSmallest ( int [ ] arr , int low , int high , int k ) { int partition = partition ( arr , low , high ) ; if ( partition == k - 1 ) return arr [ partition ] ; else if ( partition < k - 1 ) return kthSmallest ( arr , partition + 1 , high , k ) ; else return kthSmallest ( arr , low , partition - 1 , k ) ; } public static void main ( String [ ] args ) { int [ ] array = new int [ ] { 10 , 4 , 5 , 8 , 6 , 11 , 26 } ; int [ ] arraycopy = new int [ ] { 10 , 4 , 5 , 8 , 6 , 11 , 26 } ; int kPosition = 3 ; int length = array . length ; if ( kPosition > length ) { System . out . println ( " Index ▁ out ▁ of ▁ bound " ) ; } else { System . out . println ( " K - th ▁ smallest ▁ element ▁ in ▁ array ▁ : ▁ " + kthSmallest ( arraycopy , 0 , length - 1 , kPosition ) ) ; } } }
Recaman 's sequence | Java program to print n - th number in Recaman 's sequence ; Prints first n terms of Recaman sequence ; Create an array to store terms ; First term of the sequence is always 0 ; Fill remaining terms using recursive formula . ; If arr [ i - 1 ] - i is negative or already exists . ; Driver code
import java . io . * ; class GFG { static void recaman ( int n ) { int arr [ ] = new int [ n ] ; arr [ 0 ] = 0 ; System . out . print ( arr [ 0 ] + " ▁ , " ) ; for ( int i = 1 ; i < n ; i ++ ) { int curr = arr [ i - 1 ] - i ; int j ; for ( j = 0 ; j < i ; j ++ ) { if ( ( arr [ j ] == curr ) curr < 0 ) { curr = arr [ i - 1 ] + i ; break ; } } arr [ i ] = curr ; System . out . print ( arr [ i ] + " , ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 17 ; recaman ( n ) ; } }
Recaman 's sequence | Java program to print n - th number in Recaman 's sequence ; Prints first n terms of Recaman sequence ; Print first term and store it in a hash ; Print remaining terms using recursive formula . ; If arr [ i - 1 ] - i is negative or already exists . ; Driver code
import java . util . * ; class GFG { static void recaman ( int n ) { if ( n <= 0 ) return ; System . out . printf ( " % d , ▁ " , 0 ) ; HashSet < Integer > s = new HashSet < Integer > ( ) ; s . add ( 0 ) ; int prev = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int curr = prev - i ; if ( curr < 0 || s . contains ( curr ) ) curr = prev + i ; s . add ( curr ) ; System . out . printf ( " % d , ▁ " , curr ) ; prev = curr ; } } public static void main ( String [ ] args ) { int n = 17 ; recaman ( n ) ; } }
Find index of an extra element present in one sorted array | Java code for above approach ; Function to find Index ; Calculating extra element ; returns index of extra element ; function return sum of array elements ; function return index of given element ; Driver Code
class GFG { static int find_extra_element_index ( int [ ] arrA , int [ ] arrB ) { int extra_element = sum ( arrA ) - sum ( arrB ) ; return indexOf ( arrA , extra_element ) ; } static int sum ( int [ ] arr ) { int sum = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { sum += arr [ i ] ; } return sum ; } static int indexOf ( int [ ] arr , int element ) { for ( int i = 0 ; i < arr . length ; i ++ ) { if ( arr [ i ] == element ) { return i ; } } return - 1 ; } public static void main ( String [ ] args ) { int [ ] arrA = { 2 , 4 , 6 , 8 , 10 , 12 , 13 } ; int [ ] arrB = { 2 , 4 , 6 , 8 , 10 , 12 } ; System . out . println ( find_extra_element_index ( arrA , arrB ) ) ; } }
Largest subset whose all elements are Fibonacci numbers | Java program to find largest Fibonacci subset ; Prints largest subset of an array whose all elements are fibonacci numbers ; Find maximum element in arr [ ] ; Generate all Fibonacci numbers till max and store them ; Now iterate through all numbers and quickly check for Fibonacci ; Driver code
import java . util . * ; class GFG { public static void findFibSubset ( Integer [ ] x ) { List < Integer > fib = new ArrayList < Integer > ( ) ; List < Integer > result = new ArrayList < Integer > ( ) ; Integer max = Collections . max ( Arrays . asList ( x ) ) ; Integer a = 0 ; Integer b = 1 ; while ( b < max ) { Integer c = a + b ; a = b ; b = c ; fib . add ( c ) ; } for ( Integer i = 0 ; i < x . length ; i ++ ) { if ( fib . contains ( x [ i ] ) ) { result . add ( x [ i ] ) ; } } System . out . println ( result ) ; } public static void main ( String args [ ] ) { Integer [ ] a = { 4 , 2 , 8 , 5 , 20 , 1 , 40 , 13 , 23 } ; findFibSubset ( a ) ; } }
Pairs of Amicable Numbers | Efficient Java program to count Amicable pairs in an array . ; Calculate the sum of proper divisors ; 1 is a proper divisor ; To handle perfect squares ; Check if pair is amicable ; This function prints count of amicable pairs present in the input array ; Map to store the numbers ; Iterate through each number , and find the sum of proper divisors and check if it 's  also present in the array ; It 's sum of proper divisors ; As the pairs are counted twice , thus divide by 2 ; Driver code
import java . util . * ; class GFG { static int sumOfDiv ( int x ) { int sum = 1 ; for ( int i = 2 ; i <= Math . sqrt ( x ) ; i ++ ) { if ( x % i == 0 ) { sum += i ; if ( x / i != i ) sum += x / i ; } } return sum ; } static boolean isAmicable ( int a , int b ) { return ( sumOfDiv ( a ) == b && sumOfDiv ( b ) == a ) ; } static int countPairs ( int arr [ ] , int n ) { HashSet < Integer > s = new HashSet < Integer > ( ) ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) s . add ( arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . contains ( sumOfDiv ( arr [ i ] ) ) ) { int sum = sumOfDiv ( arr [ i ] ) ; if ( isAmicable ( arr [ i ] , sum ) ) count ++ ; } } return count / 2 ; } public static void main ( String [ ] args ) { int arr1 [ ] = { 220 , 284 , 1184 , 1210 , 2 , 5 } ; int n1 = arr1 . length ; System . out . println ( countPairs ( arr1 , n1 ) ) ; int arr2 [ ] = { 2620 , 2924 , 5020 , 5564 , 6232 , 6368 } ; int n2 = arr2 . length ; System . out . println ( countPairs ( arr2 , n2 ) ) ; } }