Skip to content

413. Arithmetic Slices 👍

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
class Solution {
 public:
  int numberOfArithmeticSlices(vector<int>& A) {
    const int n = A.size();
    if (n < 3)
      return 0;

    vector<int> dp(n);  // # arithmetic slices ends at i

    for (int i = 2; i < A.size(); ++i)
      if (A[i] - A[i - 1] == A[i - 1] - A[i - 2])
        dp[i] = dp[i - 1] + 1;

    return accumulate(begin(dp), end(dp), 0);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int numberOfArithmeticSlices(int[] A) {
    final int n = A.length;
    if (n < 3)
      return 0;

    int[] dp = new int[n]; // dp[i] := # of arithmetic slices ends at A[i]

    for (int i = 2; i < n; ++i)
      if (A[i] - A[i - 1] == A[i - 1] - A[i - 2])
        dp[i] += dp[i - 1] + 1;

    return Arrays.stream(dp).sum();
  }
}

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
class Solution {
 public:
  int numberOfArithmeticSlices(vector<int>& A) {
    int ans = 0;
    int dp = 0;  // # arithmetic slices ends at i

    for (int i = 2; i < A.size(); ++i)
      if (A[i] - A[i - 1] == A[i - 1] - A[i - 2])
        ans += ++dp;
      else
        dp = 0;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int numberOfArithmeticSlices(int[] A) {
    int ans = 0;
    int dp = 0;

    for (int i = 2; i < A.length; ++i) {
      if (A[i] - A[i - 1] == A[i - 1] - A[i - 2])
        ans += ++dp;
      else
        dp = 0;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def numberOfArithmeticSlices(self, A: List[int]) -> int:
    ans = 0
    dp = 0

    for i in range(2, len(A)):
      if A[i] - A[i - 1] == A[i - 1] - A[i - 2]:
        dp += 1
        ans += dp
      else:
        dp = 0

    return ans