Find the repeating element in an Array of size N consisting of first M natural numbers | Java Program for the above approach ; Function to calculate the repeating character in a given permutation ; variables to store maximum element and sum of the array respectively . ; calculate sum of array ; calculate maximum element in the array ; calculating sum of permutation ; calculate required answer ; Driver code ; Input ; Function call
import java . io . * ; class GFG { public static int repeatingElement ( int arr [ ] , int N ) { int M = 0 , sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; M = Math . max ( M , arr [ i ] ) ; } int sum1 = M * ( M + 1 ) / 2 ; int ans = ( sum - sum1 ) / ( N - M ) ; return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 6 , 4 , 3 , 1 , 5 , 2 } ; int N = arr . length ; System . out . println ( repeatingElement ( arr , N ) ) ; } }