Skip to content

1502. Can Make Arithmetic Progression From Sequence 👍

Approach 1: $O(n)$ space

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  bool canMakeArithmeticProgression(vector<int>& arr) {
    const int n = arr.size();
    const int mx = ranges::max(arr);
    const int mn = ranges::min(arr);
    const int range = mx - mn;
    if (range % (n - 1) != 0)
      return false;
    const int diff = range / (n - 1);
    if (diff == 0)
      return true;

    unordered_set<int> seen;

    for (const int a : arr) {
      if ((a - min) % diff != 0)
        return false;
      if (!seen.insert(a).second)
        return false;
    }

    return true;
  }
};

Approach 2: $O(1)$ space

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
 public:
  bool canMakeArithmeticProgression(vector<int>& arr) {
    const int n = arr.size();
    const int mx = ranges::max(arr);
    const int mn = ranges::min(arr);
    const int range = mx - mn;
    if (range % (n - 1) != 0)
      return false;
    const int diff = range / (n - 1);
    if (diff == 0)
      return true;

    for (int i = 0; i < n;) {
      const int gap = arr[i] - mn;
      if (gap % diff != 0)
        return false;
      if (gap == i * diff) {
        ++i;
      } else {
        const int rightIndex = gap / diff;
        swap(arr[i], arr[rightIndex]);
      }
    }

    return true;
  }
};