![]() |
VOOZH | about |
A sequence of numbers is called an Arithmetic progression if the difference between any two consecutive terms is always the same.
👁 ImageGiven 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
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.
Yes
Time Complexity : O(n log n)
Auxiliary Space: O(1)
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.
Yes
Time Complexity : O(n)
Auxiliary Space: O(n)
Basic Program related to Arithmetic Progression