[LeetCode] Can Make Arithmetic Progression From Sequence

1502. Can Make Arithmetic Progression From Sequence

A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.

Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false.

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public:
bool canMakeArithmeticProgression(vector<int>& arr) {
int mi = INT_MAX, ma = INT_MIN;
unordered_set<int> s;
for(auto n : arr) {
mi = min(mi, n);
ma = max(ma, n);
s.insert(n);
}

int diff = (ma - mi) / (arr.size() - 1);
while(mi != ma) {
if(!s.count(mi + diff)) return false;
mi += diff;
}
return true;
}
};
  • Time : O(nlogn)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
bool canMakeArithmeticProgression(vector<int>& arr) {
sort(arr.begin(), arr.end());
int diff = arr[0] - arr[1];
for(int i = 1; i < arr.size() - 1; i++) {
if(arr[i] - arr[i+1] != diff) return false;
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/28/PS/LeetCode/can-make-arithmetic-progression-from-sequence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.