Add the arithmetic sum of the length of each alternating array
Approach\nThe number of subarrays of any given array can be found by calculating the arithmethic sum of the length of that array (0 + 1 + 2 + 3 ... + n - 1 + n)
# Approach\nThe number of subarrays of any given array can be found by calculating the arithmethic sum of the length of that array (0 + 1 + 2 + 3 ... + n - 1 + n), where n is the length of the subarray of alternating numbers.\n\nE.g. the number of subarrays of an array of length 4 = 4 + 3 + 2 + 1 = 10.\n\nSimply calculate the arithmetic sum of each length in which all elements are alternating for that given window.\n\nE.g.:\n[0,1,1,1]\n[0]: length of alternating elements subarray is 1\n[0,1]: length of alternating elements subarray is 2\n[0,1,1]: curr element = prev element. add arithmetic sum of 2 to the res. Length of alternating elements subarray is 1.\n[0,1,1,1]: curr element = prev element. add arithmetic sum of 1 to the res. Length of alternating elements subarray is 1.\n\nAdd arithmetic sum of final length of alternating elements subarray 1 to the res.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```python3 []\nclass Solution:\n    def countAlternatingSubarrays(self, nums: List[int]) -> int:\n        # use mathematical formula subarrays = n * (n +1) // 2\n        curr_alternating_length = 0\n        res = 0\n\n        def arithmetic_sum(x):\n            return x*(x+1)//2\n\n        for i, num in enumerate(nums):\n            if i > 0 and num != nums[i-1]:\n                curr_alternating_length += 1\n            else:\n                res += arithmetic_sum(curr_alternating_length)\n                curr_alternating_length = 1\n\n        return res + arithmetic_sum(curr_alternating_length)\n\n```
['Python3']