Given an array of n integers. The task is to check whether an arithmetic progression can be formed using all the given elements. If possible print “Yes”, else print “No”.
Examples:
Input : arr[] = {0, 12, 4, 8}
Output : Yes
Rearrange given array as {0, 4, 8, 12}
which forms an arithmetic progression.
Input : arr[] = {12, 40, 11, 20}
Output : No
Method 1 (Simple)
A simple solution is to first find the smallest element, then find second smallest element and find the difference between these two. Let this difference be d. After finding the difference, find third smallest, fourth smallest and so on. After finding every i-th smallest (from third onward), find the difference between value of current element and value of previous element. If difference is not same as d, return false. If all elements have same difference, return true. Time complexity of this solution is O(n2)
Method 2(Use Sorting)
The idea is to sort the given array. After sorting, check if differences between consecutive elements are same or not. If all differences are same, Arithmetic Progression is possible.
Below is the implementation of this approach:
C++
#include<bits/stdc++.h>
using namespace std;
bool checkIsAP( int arr[], int n)
{
if (n == 1)
return true ;
sort(arr, arr + n);
int d = arr[1] - arr[0];
for ( int i=2; i<n; i++)
if (arr[i] - arr[i-1] != d)
return false ;
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;
}
|
Java
import java.util.Arrays;
class GFG {
static boolean checkIsAP( int arr[], int n)
{
if (n == 1 )
return true ;
Arrays.sort(arr);
int d = arr[ 1 ] - arr[ 0 ];
for ( int i = 2 ; i < n; i++)
if (arr[i] - arr[i- 1 ] != d)
return false ;
return true ;
}
public static void main (String[] args)
{
int arr[] = { 20 , 15 , 5 , 0 , 10 };
int n = arr.length;
if (checkIsAP(arr, n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def checkIsAP(arr, n):
if (n = = 1 ): return True
arr.sort()
d = arr[ 1 ] - arr[ 0 ]
for i in range ( 2 , n):
if (arr[i] - arr[i - 1 ] ! = d):
return False
return True
arr = [ 20 , 15 , 5 , 0 , 10 ]
n = len (arr)
print ( "Yes" ) if (checkIsAP(arr, n)) else print ( "No" )
|
C#
using System;
class GFG {
static bool checkIsAP( int []arr, int n)
{
if (n == 1)
return true ;
Array.Sort(arr);
int d = arr[1] - arr[0];
for ( int i = 2; i < n; i++)
if (arr[i] - arr[i - 1] != d)
return false ;
return true ;
}
public static void Main ()
{
int []arr = {20, 15, 5, 0, 10};
int n = arr.Length;
if (checkIsAP(arr, n))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
PHP
<?php
function checkIsAP( $arr , $n )
{
if ( $n == 1)
return true;
sort( $arr );
$d = $arr [1] - $arr [0];
for ( $i = 2; $i < $n ; $i ++)
if ( $arr [ $i ] -
$arr [ $i - 1] != $d )
return false;
return true;
}
$arr = array (20, 15, 5, 0, 10);
$n = count ( $arr );
if (checkIsAP( $arr , $n ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function checkIsAP(arr, n)
{
if (n == 1)
return true ;
arr.sort((a, b) => a - b);
let d = arr[1] - arr[0];
for (let i=2; i<n; i++)
if (arr[i] - arr[i-1] != d)
return false ;
return true ;
}
let arr = [ 20, 15, 5, 0, 10 ];
let n = arr.length;
(checkIsAP(arr, n))? (document.write( "Yes" + "<br>" )) :
(document.write( "No" + "<br>" ));
</script>
|
Time Complexity: O(n Log n).
Auxiliary Space: O(1)
Method 3(Use Hashing)
- Find out the smallest and second smallest elements
- Find difference between the two elements. d = second_smallest – smallest
- Store all elements in a hashmap and return “NO” if duplicate element found (can be done together with step 1).
- Now start from “second smallest element + d” and one by one check n-2 terms of Arithmetic Progression in hashmap. If any value of progression is missing, return false.
- Return “YES” after end of the loop.
Below is the implementation of this method.
C++
#include <bits/stdc++.h>
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;
}
|
Java
import java.util.HashMap;
class GFG {
static boolean checkIsAP( int arr[], int n) {
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
int smallest = Integer.MAX_VALUE, second_smallest = Integer.MAX_VALUE;
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.containsKey(arr[i])) {
hm.put(arr[i], 1 );
}
else
return false ;
}
int diff = second_smallest - smallest;
for ( int i = 0 ; i < n - 1 ; i++) {
if (!hm.containsKey(second_smallest))
return false ;
second_smallest += diff;
}
return true ;
}
public static void main(String args[]) {
int arr[] = { 20 , 15 , 5 , 0 , 10 };
int n = arr.length;
if (checkIsAP(arr, n)) {
System.out.println( "Yes" );
} else {
System.out.println( "No" );
}
;
}
}
|
Python3
def checkIsAP(arr, n):
hm = {}
smallest = float ( 'inf' )
second_smallest = float ( 'inf' )
for i in range (n):
if (arr[i] < smallest):
second_smallest = smallest
smallest = arr[i]
else if (arr[i] ! = smallest and
arr[i] < second_smallest):
second_smallest = arr[i]
if arr[i] not in hm:
hm[arr[i]] = 1
else :
return False
diff = second_smallest - smallest
for i in range (n - 1 ):
if (second_smallest) not in hm:
return False
second_smallest + = diff
return True
arr = [ 20 , 15 , 5 , 0 , 10 ]
n = len (arr)
if (checkIsAP(arr, n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public static bool checkIsAP( int [] arr, int n) {
Dictionary< int , int > hm = new Dictionary< int , int >();
int smallest = Int32.MaxValue, second_smallest = Int32.MaxValue;
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.ContainsKey(arr[i])) {
hm[arr[i]]= 1;
}
else
return false ;
}
int diff = second_smallest - smallest;
for ( int i = 0; i < n - 1; i++) {
if (!hm.ContainsKey(second_smallest))
return false ;
second_smallest += diff;
}
return true ;
}
public static void Main( string [] args) {
int [] arr = { 20, 15, 5, 0, 10 };
int n = arr.Length;
if (checkIsAP(arr, n)) {
Console.WriteLine( "Yes" );
} else {
Console.WriteLine( "No" );
}
}
}
|
Javascript
<script>
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( "Yes" ))
: (document.write( "No" ));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Thanks to Chenna Rao for suggesting this method,
Method 4(Using counting sort)
We can reduce space required in method 3 if given array can be modified.
- Find smallest and second smallest elements.
- Find d = second_smallest – smallest
- Subtract smallest element from all elements.
- Now if given array represent AP, all elements should be of form i*d where i varies from 0 to n-1.
- One by one divide all reduced elements with d. If any element is not divisible by d, return false.
- Now if array represents AP, it must be a permutation of numbers from 0 to n-1. We can easily check this using counting sort.
C++
#include <bits/stdc++.h>
using namespace std;
bool countingsort( int arr[], int n)
{
int count[n] = { 0 };
for ( int i = 0; i < n; i++) {
count[arr[i]]++;
}
for ( int i = 0; i <= n-1; i++) {
if (count[i] != 1)
return false ;
}
return true ;
}
bool checkIsAP( int arr[], int n)
{
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];
}
int diff = second_smallest - smallest;
for ( int i = 0; i < n; i++) {
arr[i]=arr[i]-smallest;
}
for ( int i=0;i<n;i++)
{
if (arr[i]%diff!=0)
{
return false ;
}
else
{
arr[i]=arr[i]/diff;
}
}
if (countingsort(arr,n))
return true ;
else
return false ;
}
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;
}
|
Java
import java.io.*;
class GFG {
static boolean countingsort( int arr[], int n)
{
int [] count = new int [n];
for ( int i = 0 ; i < n; i++)
count[i] = 0 ;
for ( int i = 0 ; i < n; i++) {
count[arr[i]]++;
}
for ( int i = 0 ; i <= n- 1 ; i++) {
if (count[i] != 1 )
return false ;
}
return true ;
}
static boolean checkIsAP( int arr[], int n)
{
int smallest = Integer.MAX_VALUE, second_smallest = Integer.MAX_VALUE ;
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];
}
int diff = second_smallest - smallest;
for ( int i = 0 ; i < n; i++) {
arr[i] = arr[i] - smallest;
}
for ( int i = 0 ; i < n; i++)
{
if (arr[i] % diff != 0 )
{
return false ;
}
else
{
arr[i] = arr[i]/diff;
}
}
if (countingsort(arr,n))
return true ;
else
return false ;
}
public static void main (String[] args)
{
int arr[] = { 20 , 15 , 5 , 0 , 10 };
int n = arr.length;
if (checkIsAP(arr, n))
System.out.println( "Yes" );
else System.out.println( "No" );
}
}
|
Python3
import sys
def countingsort( arr, n):
count = [ 0 ] * n;
for i in range ( 0 , n):
count[arr[i]] + = 1 ;
for i in range ( 0 , n - 1 ):
if (count[i] ! = 1 ):
return False ;
return True ;
def checkIsAP( arr, n):
smallest = sys.maxsize;
second_smallest = sys.maxsize;
for i in range ( 0 ,n):
if (arr[i] < smallest) :
second_smallest = smallest;
smallest = arr[i];
elif (arr[i] ! = smallest and arr[i] < second_smallest):
second_smallest = arr[i];
diff = second_smallest - smallest;
for i in range ( 0 ,n):
arr[i] = arr[i] - smallest;
for i in range ( 0 ,n):
if (arr[i] % diff! = 0 ):
return False ;
else :
arr[i] = ( int )(arr[i] / diff);
if (countingsort(arr,n)):
return True ;
else :
return False ;
arr = [ 20 , 15 , 5 , 0 , 10 ];
n = len (arr);
if (checkIsAP(arr, n)):
print ( "Yes" );
else :
print ( "NO" );
|
Javascript
function countingsort( arr, n)
{
let count= new Array(n).fill(0);
for (let i = 0; i < n; i++) {
count[arr[i]]++;
}
for (let i = 0; i <= n-1; i++) {
if (count[i] != 1)
return false ;
}
return true ;
}
function checkIsAP( arr, n)
{
let smallest = Number.MAX_SAFE_INTEGER, second_smallest = Number.MAX_SAFE_INTEGER;
for (let 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];
}
let diff = second_smallest - smallest;
for (let i = 0; i < n; i++) {
arr[i]=arr[i]-smallest;
}
for (let i=0;i<n;i++)
{
if (arr[i]%diff!=0)
{
return false ;
}
else
{
arr[i]=arr[i]/diff;
}
}
if (countingsort(arr,n))
return true ;
else
return false ;
}
let arr = [20, 15, 5, 0, 10 ];
let n = arr.length;
(checkIsAP(arr, n)) ? (console.log( "Yes\n" ))
: (console.log( "No\n" ));
|
C#
using System;
class GFG
{
static bool CountingSort( int [] arr, int n)
{
int [] count = new int [n];
for ( int i = 0; i < n; i++)
{
count[arr[i]]++;
}
for ( int i = 0; i <= n - 1; i++)
{
if (count[i] != 1)
{
return false ;
}
}
return true ;
}
static bool CheckIsAP( int [] arr, int n)
{
int smallest = int .MaxValue;
int secondSmallest = int .MaxValue;
for ( int i = 0; i < n; i++)
{
if (arr[i] < smallest)
{
secondSmallest = smallest;
smallest = arr[i];
}
else if (arr[i] != smallest && arr[i] < secondSmallest)
{
secondSmallest = arr[i];
}
}
int diff = secondSmallest - smallest;
for ( int i = 0; i < n; i++)
{
arr[i] = arr[i] - smallest;
}
for ( int i = 0; i < n; i++)
{
if (arr[i] % diff != 0)
{
return false ;
}
else
{
arr[i] = arr[i] / diff;
}
}
if (CountingSort(arr, n))
{
return true ;
}
else
{
return false ;
}
}
static void Main( string [] args)
{
int [] arr = new int [] { 20, 15, 5, 0, 10 };
int n = arr.Length;
Console.WriteLine(CheckIsAP(arr, n) ? "Yes" : "No" );
}
}
|
Time Complexity – O(n)
Auxiliary Space – O(n)
Method 5( Hashing with Single Pass)
The basic idea is to find the common difference of the AP by finding out the maximum and the minimum element of the array. After that start from the maximum value and keep on decreasing the value by the common difference alongside checking that whether this new value is present in the hashmap or not . If at any point the value isn’t present in the hashset , break the loop . The ideal situation after the loop breaking is that all n elements have been covered and if yes , then return true else return false.
C++
#include <bits/stdc++.h>
using namespace std;
bool checkIsAP( int arr[], int n)
{
unordered_set< int > st;
int maxi = INT_MIN;
int mini = INT_MAX;
for ( int i=0;i<n;i++) {
maxi = max(arr[i], maxi);
mini = min(arr[i], mini);
st.insert(arr[i]);
}
int diff = (maxi - mini) / (n - 1);
int count = 0;
while (st.find(maxi)!=st.end()) {
count++;
maxi = maxi - diff;
}
if (count == n)
return true ;
return false ;
}
int main()
{
int arr[] = { 0, 12, 4, 8 };
int n = 4;
cout << boolalpha << checkIsAP(arr, n);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
int [] arr = { 0 , 12 , 4 , 8 };
int n = arr.length;
System.out.println(checkIsAP(arr, n));
}
static boolean checkIsAP( int arr[], int n)
{
HashSet<Integer> set = new HashSet<Integer>();
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for ( int i : arr) {
max = Math.max(i, max);
min = Math.min(i, min);
set.add(i);
}
int diff = (max - min) / (n - 1 );
int count = 0 ;
while (set.contains(max)) {
count++;
max = max - diff;
}
if (count == arr.length)
return true ;
return false ;
}
}
|
Python3
import sys
def checkIsAP(arr, n):
Set = set ()
Max = - sys.maxsize - 1
Min = sys.maxsize
for i in arr:
Max = max (i, Max )
Min = min (i, Min )
Set .add(i)
diff = ( Max - Min ) / / (n - 1 )
count = 0
while ( Max in Set ):
count + = 1
Max = Max - diff
if (count = = len (arr)):
return True
return False
arr = [ 0 , 12 , 4 , 8 ]
n = len (arr)
print (checkIsAP(arr, n))
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
static bool checkIsAP( int [] arr, int n)
{
HashSet< int > st = new HashSet< int >();
int maxi = int .MinValue;
int mini = int .MaxValue;
for ( int i = 0; i < n; i++) {
maxi = Math.Max(arr[i], maxi);
mini = Math.Min(arr[i], mini);
st.Add(arr[i]);
}
int diff = (maxi - mini) / (n - 1);
int count = 0;
while (st.Contains(maxi)) {
count++;
maxi = maxi - diff;
}
if (count == n) {
return true ;
}
return false ;
}
internal static void Main()
{
int [] arr = { 0, 12, 4, 8 };
int n = 4;
Console.Write(checkIsAP(arr, n));
}
}
|
Javascript
<script>
function checkIsAP(arr, n){
set = new Set()
let Max = Number.MIN_VALUE
let Min = Number.MAX_VALUE
for (let i of arr){
Max = Math.max(i, Max)
Min = Math.min(i, Min)
set.add(i)
}
let diff = Math.floor((Max - Min) / (n - 1))
let count = 0
while (set.has(Max)){
count += 1
Max = Max - diff
}
if (count == arr.length)
return true
return false
}
let arr = [ 0, 12, 4, 8 ]
let n = arr.length
document.write(checkIsAP(arr, n))
</script>
|
Time Complexity – O(n)
Auxiliary Space – O(n)
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.