In this Leetcode Arithmetic Slices problem solution, An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.

Given an integer array nums, return the number of arithmetic subarrays of nums. A subarray is a contiguous subsequence of the array.

Leetcode Arithmetic Slices problem solution


Problem solution in Python.

class Solution:
    def numberOfArithmeticSlices(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        if len(A) < 3:
            return 0
        diff = A[1] - A[0]
        element_count = 2
        result_count = 1
        total = 0
        for i in range(2,len(A)):
            if diff == A[i] - A[i-1]:
                element_count += 1
                if element_count >= 3:
                    total += result_count
                    result_count += 1
            else:
                diff = A[i] - A[i-1]
                element_count = 2
                result_count = 1
        return total



Problem solution in Java.

public int numberOfArithmeticSlices(int[] A) {
        int n = A.length;
        if (n < 3) return 0;
        HashMap<Integer, Integer> map = new HashMap();
        int start = A[0];
        int diff = A[1] - A[0];
        int len = 2;
        for (int i = 2; i < n; i++) {
            if (A[i] - A[i-1] == diff) {
                len++;
                map.put(start, len);
            } else {
                start = A[i-1];
                diff = A[i] - A[i-1];
                len = 2;
            }
        }
        
        int res = 0;
        for (int key: map.keySet()) {
            int length = map.get(key);
            int num_seq = length-2;
            res += (1 + num_seq) * num_seq / 2;
        }
        return res;
    }


Problem solution in C++.

class Solution {
public:
    int numberOfArithmeticSlices(vector<int>& A) {
        if(A.size()<3) return 0;
        int diff=A[1]-A[0];
        int len=2;
        int res=0;
        for(int i = 2 ; i < A.size(); ++i){
            len++;
            if(!(len>=3&&A[i]-A[i-1]==diff))
                len = 2;
            diff = A[i]-A[i-1];
            res += len -2 ;
        }
        return res;
    }
};


Problem solution in C.

int numberOfArithmeticSlices(int* A, int ASize) {
    int prev = 0, curr, ans = 0;
    for(int i = 2; i < ASize; i++){
        curr = 0;
        if(A[i] - A[i-1] == A[i-1] - A[i-2]){
            curr = prev + 1;
        }
        prev = curr;
        ans = ans + curr;
    }
    return ans;
}