A sequence of numbers is called an Arithmetic progression if the difference between any two consecutive terms is always the same.

Given an array arr[] of integers. Write a program to check whether an arithmetic progression can be formed using all the given elements.
Examples:
Input: arr[] = [0, 12, 4, 8]
Output: true
Explanation: Rearrange given array as [0, 4, 8, 12] which forms an arithmetic progression.
Input: arr[] = [12, 40, 11, 20]
Output: false
Explanation: there is no rearrangement which can form an arithmetic progression.
Table of Content
[Naive Approach] Using Sorting – O(n log n) Time O(1) Space
The idea is to sort the array, then check if the difference between every pair of consecutive elements is the same. If yes, it forms an AP; otherwise, it does not.
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool checkIsAP(vector<int> &arr)
{
int n = arr.size();
if (n == 1)
return true;
// Sort array
sort(arr.begin(), arr.end());
// 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
int main()
{
vector<int> arr = {20, 15, 5, 0, 10};
if (checkIsAP(arr))
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}
import java.util.Arrays;
public class GfG {
public static boolean checkIsAP(int[] arr) {
int n = arr.length;
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;
}
public static void main(String[] args) {
int[] arr = {20, 15, 5, 0, 10};
if (checkIsAP(arr))
System.out.println("Yes");
else
System.out.println("No");
}
}
def checkIsAP(arr):
n = len(arr)
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
if __name__ == "__main__":
arr = [20, 15, 5, 0, 10]
if checkIsAP(arr):
print("Yes")
else:
print("No")
using System;
using System.Linq;
public class GfG
{
public static bool checkIsAP(int[] arr)
{
int n = arr.Length;
if (n == 1)
return true;
// Sort array
Array.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;
}
public static void Main()
{
int[] arr = {20, 15, 5, 0, 10};
if (checkIsAP(arr))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
function checkIsAP(arr) {
let n = arr.length;
if (n == 1)
return true;
// Sort array
arr.sort((a, b) => a - b);
// After sorting, difference between
// consecutive elements must be same.
let d = arr[1] - arr[0];
for (let i = 2; i < n; i++)
if (arr[i] - arr[i - 1]!= d)
return false;
return true;
}
// Driver Code
let arr = [20, 15, 5, 0, 10];
if (checkIsAP(arr))
console.log('Yes');
else
console.log('No');
Output
Yes
Time Complexity : O(n log n)
Auxiliary Space: O(1)
[Expected Approach] Using Hashing with Single Pass – O(n) Time, O(n) Space
The idea is to find the minimum and maximum elements to compute the common difference as
(max - min) / (n - 1). If this difference is not an integer, the array cannot form an AP. Store all elements in a hash set, then check whether every expected termmin + i * diffexists in the set fori = 0 to n-1. If all elements are present, the array can form an AP.
#include <bits/stdc++.h>
#include <algorithm>
#include <vector>
using namespace std;
bool checkIsAP(vector<int> &arr)
{
int n = arr.size();
if (n <= 2)
return true;
unordered_set<int> st;
int mini = INT_MAX, maxi = INT_MIN;
// Find min, max and insert into set
for (int i = 0; i < n; i++)
{
mini = min(mini, arr[i]);
maxi = max(maxi, arr[i]);
st.insert(arr[i]);
}
// handle duplicates
if (st.size() != n)
{
// Only valid if all elements are same
return (maxi == mini);
}
// If diff is not integer is not AP
if ((maxi - mini) % (n - 1) != 0)
return false;
int diff = (maxi - mini) / (n - 1);
// Check all elements of AP exist
for (int i = 0; i < n; i++)
{
int val = mini + i * diff;
if (st.find(val) == st.end())
return false;
}
return true;
}
// Driver Code
int main()
{
vector<int> arr = {20, 15, 5, 0, 10};
if (checkIsAP(arr))
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}
import java.util.HashSet;
import java.util.Set;
public class GfG {
public static boolean checkIsAP(int[] arr) {
int n = arr.length;
if (n <= 2) return true;
Set<Integer> st = new HashSet<>();
int mini = Integer.MAX_VALUE, maxi = Integer.MIN_VALUE;
// Find min, max and insert into set
for (int i = 0; i < n; i++) {
mini = Math.min(mini, arr[i]);
maxi = Math.max(maxi, arr[i]);
st.add(arr[i]);
}
// handle duplicates
if (st.size()!= n) {
// Only valid if all elements are same
return (maxi == mini);
}
// If diff is not integer is not AP
if ((maxi - mini) % (n - 1)!= 0)
return false;
int diff = (maxi - mini) / (n - 1);
// Check all elements of AP exist
for (int i = 0; i < n; i++) {
int val = mini + i * diff;
if (!st.contains(val))
return false;
}
return true;
}
public static void main(String[] args) {
int[] arr = {20, 15, 5, 0, 10};
if (checkIsAP(arr))
System.out.println("Yes");
else
System.out.println("No");
}
}
def checkIsAP(arr):
n = len(arr)
if n <= 2:
return True
st = set()
mini = float('inf')
maxi = float('-inf')
# Find min, max and insert into set
for i in range(n):
mini = min(mini, arr[i])
maxi = max(maxi, arr[i])
st.add(arr[i])
# handle duplicates
if len(st)!= n:
# Only valid if all elements are same
return maxi == mini
# If diff is not integer is not AP
if (maxi - mini) % (n - 1)!= 0:
return False
diff = (maxi - mini) // (n - 1)
# Check all elements of AP exist
for i in range(n):
val = mini + i * diff
if val not in st:
return False
return True
# Driver Code
if __name__ == "__main__":
arr = [20, 15, 5, 0, 10]
if checkIsAP(arr):
print("Yes")
else:
print("No")
using System;
using System.Collections.Generic;
public class GfG
{
public static bool checkIsAP(int[] arr)
{
int n = arr.Length;
if (n <= 2)
return true;
HashSet<int> st = new HashSet<int>();
int mini = int.MaxValue, maxi = int.MinValue;
// Find min, max and insert into set
for (int i = 0; i < n; i++)
{
mini = Math.Min(mini, arr[i]);
maxi = Math.Max(maxi, arr[i]);
st.Add(arr[i]);
}
// handle duplicates
if (st.Count!= n)
{
// Only valid if all elements are same
return (maxi == mini);
}
// If diff is not integer is not AP
if ((maxi - mini) % (n - 1)!= 0)
return false;
int diff = (maxi - mini) / (n - 1);
// Check all elements of AP exist
for (int i = 0; i < n; i++)
{
int val = mini + i * diff;
if (!st.Contains(val))
return false;
}
return true;
}
public static void Main()
{
int[] arr = { 20, 15, 5, 0, 10 };
if (checkIsAP(arr))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
function checkIsAP(arr) {
let n = arr.length;
if (n <= 2) return true;
let st = new Set();
let mini = Number.MAX_SAFE_INTEGER;
let maxi = Number.MIN_SAFE_INTEGER;
// Find min, max and insert into set
for (let i = 0; i < n; i++) {
mini = Math.min(mini, arr[i]);
maxi = Math.max(maxi, arr[i]);
st.add(arr[i]);
}
// handle duplicates
if (st.size!= n) {
// Only valid if all elements are same
return maxi === mini;
}
// If diff is not integer is not AP
if ((maxi - mini) % (n - 1)!= 0) return false;
let diff = Math.floor((maxi - mini) / (n - 1));
// Check all elements of AP exist
for (let i = 0; i < n; i++) {
let val = mini + i * diff;
if (!st.has(val)) return false;
}
return true;
}
// Driver Code
let arr = [20, 15, 5, 0, 10];
if (checkIsAP(arr))
console.log('Yes');
else
console.log('No');
Output
Yes
Time Complexity : O(n)
Auxiliary Space: O(n)
Basic Program related to Arithmetic Progression
- Program for sum of arithmetic series
- Program to print Arithmetic Progression series
- Longest arithmetic progression with the given common difference
- Check whether Arithmetic Progression can be formed from the given array
- Find the missing number in Arithmetic Progression
- Find N Arithmetic Means between A and B
- Sum of the numbers upto N that are divisible by 2 or 5
- Find First element in AP which is multiple of given prime
More problems related to Arithmetic Progression
- Sum of first n terms of a given series 3, 6, 11, …..
- Ratio of mth and nth terms of an A. P. with given ratio of sums
- Probability for three randomly chosen numbers to be in AP
- Print all triplets in sorted array that form AP
- Program for N-th term of Arithmetic Progression series
- Sum of Arithmetic Geometric Sequence
- Count of AP (Arithmetic Progression) Subsequences in an array