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

    vector<int> dp(
        n);  // dp[i] := the number of arithmetic slices ending in index i

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

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

    int[] dp = new int[n]; // dp[i] := the number of arithmetic slices ends in nums[i]

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

    return Arrays.stream(dp).sum();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def numberOfArithmeticSlices(self, nums: list[int]) -> int:
    n = len(nums)
    if n < 3:
      return 0

    dp = [0] * n  # dp[i] := the number of arithmetic slices ending in index i

    for i in range(2, len(nums)):
      if nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]:
        dp[i] = dp[i - 1] + 1

    return sum(dp)

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>& nums) {
    int ans = 0;
    int dp = 0;  // the number of arithmetic slices ending in index i

    for (int i = 2; i < nums.size(); ++i)
      if (nums[i] - nums[i - 1] == nums[i - 1] - nums[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[] nums) {
    int ans = 0;
    int dp = 0; // the number of arithmetic slices ending in index i

    for (int i = 2; i < nums.length; ++i) {
      if (nums[i] - nums[i - 1] == nums[i - 1] - nums[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, nums: list[int]) -> int:
    ans = 0
    dp = 0

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

    return ans