Related Articles

# Check whether Arithmetic Progression can be formed from the given array

• Difficulty Level : Medium
• Last Updated : 08 Jun, 2021

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 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++

 `// C++ program to check if a given array` `// can form arithmetic progression` `#include` `using` `namespace` `std;`   `// Returns true if a permutation of arr[0..n-1]` `// can form arithmetic progression` `bool` `checkIsAP(``int` `arr[], ``int` `n)` `{` `  ``if` `(n == 1)` `    ``return` `true``;`   `  ``// Sort array` `  ``sort(arr, arr + n);`   `  ``// After sorting, difference between` `  ``// consecutive elements must be same.` `  ``int` `d = arr - arr;` `  ``for` `(``int` `i=2; i

## Java

 `// Java program to check if a given array` `// can form arithmetic progression` `import` `java.util.Arrays;`   `class` `GFG {` `        `  `    ``// Returns true if a permutation of ` `    ``// arr[0..n-1] can form arithmetic ` `    ``// progression` `    ``static` `boolean` `checkIsAP(``int` `arr[], ``int` `n)` `    ``{` `        ``if` `(n == ``1``)` `            ``return` `true``;` `        `  `        ``// Sort array` `        ``Arrays.sort(arr);` `        `  `        ``// After sorting, difference between` `        ``// consecutive elements must be same.` `        ``int` `d = arr[``1``] - arr[``0``];` `        ``for` `(``int` `i = ``2``; i < n; i++)` `            ``if` `(arr[i] - arr[i-``1``] != d)` `                ``return` `false``;` `        `  `        ``return` `true``;` `    ``}` `    `  `    ``//driver code` `    ``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"``);` `    ``}` `}`   `// This code is contributed by Anant Agarwal.`

## Python3

 `# Python3 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` `def` `checkIsAP(arr, n):` `    ``if` `(n ``=``=` `1``): ``return` `True`   `    ``# Sort array` `    ``arr.sort()`   `    ``# After sorting, difference between` `    ``# consecutive elements must be same.` `    ``d ``=` `arr[``1``] ``-` `arr[``0``]` `    ``for` `i ``in` `range``(``2``, n):` `        ``if` `(arr[i] ``-` `arr[i``-``1``] !``=` `d):` `            ``return` `False`   `    ``return` `True`   `# Driver code` `arr ``=` `[ ``20``, ``15``, ``5``, ``0``, ``10` `]` `n ``=` `len``(arr)` `print``(``"Yes"``) ``if``(checkIsAP(arr, n)) ``else` `print``(``"No"``)`   `# This code is contributed by Anant Agarwal.`

## C#

 `// C# program to check if a given array` `// can form arithmetic progression` `using` `System;`   `class` `GFG {` `        `  `    ``// Returns true if a permutation of ` `    ``// arr[0..n-1] can form arithmetic ` `    ``// progression` `    ``static` `bool` `checkIsAP(``int` `[]arr, ``int` `n)` `    ``{` `        ``if` `(n == 1)` `            ``return` `true``;` `        `  `        ``// Sort array` `        ``Array.Sort(arr);` `        `  `        ``// After sorting, difference between` `        ``// consecutive elements must be same.` `        ``int` `d = arr - arr;` `        ``for` `(``int` `i = 2; i < n; i++)` `            ``if` `(arr[i] - arr[i - 1] != d)` `                ``return` `false``;` `        `  `        ``return` `true``;` `    ``}` `    `  `    ``//Driver Code` `    ``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"``);` `    ``}` `}`   `// This code is contributed by vt_m.`

## PHP

 ``

## Javascript

 ``

Output

`Yes`

Time Complexity: O(n Log n).

Method 3(Use Hashing)

1. Find out the smallest and second smallest elements
2. Find different between the two elements. d = second_smallest – smallest
3. Store all elements in a hashmap and return “NO” if duplicate element found (can be done together with step 1).
4. 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.
5. Return “YES” after end of the loop.

Below is the implementation of this method.

## C++

 `// C++ program to check if a given array` `// can form arithmetic progression` `#include ` `using` `namespace` `std;`   `// Returns true if a permutation of arr[0..n-1]` `// can form arithmetic progression` `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++) {` `      `  `        ``// Find the smallest and and ` `        ``// update second smallest` `        ``if` `(arr[i] < smallest) {` `            ``second_smallest = smallest;` `            ``smallest = arr[i];` `        ``}` `      `  `        ``// Find second smallest` `        ``else` `if` `(arr[i] != smallest` `                 ``&& arr[i] < second_smallest)` `            ``second_smallest = arr[i];` `      `  `        ``// Check if the duplicate element found or not` `        ``if` `(hm.find(arr[i]) == hm.end())` `            ``hm[arr[i]]++;` `      `  `        ``// If duplicate found then return false` `        ``else` `            ``return` `false``;` `    ``}` `  `  `    ``// Find the difference between smallest and second` `    ``// smallest` `  `  `    ``int` `diff = second_smallest - smallest;` `  `  `    ``// As we have used smallest and ` `    ``// second smallest,so we` `    ``// should now only check for n-2 elements` `    ``for` `(``int` `i = 0; i < n - 1; i++) {` `        ``if` `(hm.find(second_smallest) == hm.end())` `            ``return` `false``;` `        ``second_smallest += diff;` `    ``}` `    ``return` `true``;` `}`   `// Driven Program` `int` `main()` `{` `    ``int` `arr[] = { 20, 15, 5, 0, 10 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);`   `    ``(checkIsAP(arr, n)) ? (cout << ``"Yes"` `<< endl)` `                        ``: (cout << ``"No"` `<< endl);`   `    ``return` `0;`   `    ``// This code is contributed by Raman Jha` `}`

## Python3

 `# Python3 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` `def` `checkIsAP(arr, n):` `    `  `    ``hm ``=` `{}` `    ``smallest ``=` `float``(``'inf'``)` `    ``second_smallest ``=` `float``(``'inf'``)` `    `  `    ``for` `i ``in` `range``(n):` `        `  `        ``# Find the smallest and and ` `        ``# update second smallest` `        ``if` `(arr[i] < smallest):` `            ``second_smallest ``=` `smallest` `            ``smallest ``=` `arr[i]` `      `  `        ``# Find second smallest` `        ``elif` `(arr[i] !``=` `smallest ``and` `              ``arr[i] < second_smallest):` `            ``second_smallest ``=` `arr[i]` `      `  `        ``# Check if the duplicate element found or not` `        ``if` `arr[i] ``not` `in` `hm:` `            ``hm[arr[i]] ``=` `1` `            `  `        ``# If duplicate found then return false` `        ``else``:` `            ``return` `False` `  `  `    ``# Find the difference between smallest` `    ``# and second smallest` `    ``diff ``=` `second_smallest ``-` `smallest` `  `  `    ``# As we have used smallest and ` `    ``# second smallest,so we` `    ``# should now only check for n-2 elements` `    ``for` `i ``in` `range``(n``-``1``):` `        ``if` `(second_smallest) ``not` `in` `hm:` `            ``return` `False` `            `  `        ``second_smallest ``+``=` `diff` `    `  `    ``return` `True`   `# Driver code ` `arr ``=` `[ ``20``, ``15``, ``5``, ``0``, ``10` `]` `n ``=` `len``(arr)`   `if` `(checkIsAP(arr, n)):` `    ``print``(``"Yes"``)` `else``:` `    ``print``(``"No"``)` `    `  `# This code is contributed by rohitsingh07052`

## Javascript

 ``

Output

`Yes`

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.

1. Find smallest and second smallest elements.
2. Find d = second_smallest – smallest
3. Subtract smallest element from all elements.
4. Now if given array represent AP, all elements should be of form i*d where i varies from 0 to n-1.
5. One by one divide all reduced elements with d. If any element is not divisible by d, return false.
6. 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.

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.