Check whether Arithmetic Progression can be formed from the given array | Returns true if a permutation of arr [ 0. . n - 1 ] can form arithmetic progression ; Find the smallest and and update second smallest ; Find second smallest ; Check if the duplicate element found or not ; If duplicate found then return false ; Find the difference between smallest and second smallest ; As we have used smallest and second smallest , so we should now only check for n - 2 elements ; Driven Program
function checkIsAP ( arr , n ) { var hm = new Map ( ) ; var smallest = 1000000000 , second_smallest = 1000000000 ; for ( var i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < smallest ) { second_smallest = smallest ; smallest = arr [ i ] ; } else if ( arr [ i ] != smallest && arr [ i ] < second_smallest ) second_smallest = arr [ i ] ; if ( ! hm . has ( arr [ i ] ) ) { hm . set ( arr [ i ] , 1 ) ; } else return false ; } var diff = second_smallest - smallest ; for ( var i = 0 ; i < n - 1 ; i ++ ) { if ( ! hm . has ( second_smallest ) ) return false ; second_smallest += diff ; } return true ; } var arr = [ 20 , 15 , 5 , 0 , 10 ] ; var n = arr . length ; ( checkIsAP ( arr , n ) ) ? ( document . write ( " " ) ) : ( document . write ( " " ) ) ;