text: Check whether Arithmetic Progression can be formed from the given array | C ++ program to check if a given array can form arithmetic progression ; 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkIsAP ( int arr [ ] , int n ) { unordered_map < int , int > hm ; int smallest = INT_MAX , second_smallest = INT_MAX ; for ( int 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 . find ( arr [ i ] ) == hm . end ( ) ) hm [ arr [ i ] ] ++ ; else return false ; } int diff = second_smallest - smallest ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( hm . find ( second_smallest ) == hm . end ( ) ) return false ; second_smallest += diff ; } return true ; } int main ( ) { int arr [ ] = { 20 , 15 , 5 , 0 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; ( checkIsAP ( arr , n ) ) ? ( cout << " Yes " << endl ) : ( cout << " No " << endl ) ; return 0 ; }