Simple Java solution - Two pointer/Slding Window Time: O(n), Space: O(1)
Intuition\n Describe your first thoughts on how to solve this problem. \nStart from the begining and find the longest alternating Subarray. For an array of size
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nStart from the begining and find the longest alternating Subarray. For an array of size n, there are (1+2+3+...+n) **(i.e. sum of first n natural numbers)** subarrays that exist \n\nThat means for every alternating subarray of size `windowSize` there exist `((windowSize*(windowSize+1))/2)`**(formula for sum of first n natural numbers)** sub arrays. Do this for the whole array and you get rhe total number of alternating subarrays\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTake 2 pointers `l` and `r`\n\nStart incrementing `r` untill element at `r` and `r+1` are unequal, The moment you find an element at `r` being equal to element at `r+1`, you have found an aklternating subarray of size `r-l+1` \n\nNow store this size in a variable `windowSize` and increment your answer by `((windowSize*(windowSize+1))/2)` do this untill `l` doesn\'t reach the end of the array\n\n\n**IMP NOTE:  Declare this `windowSize` variable as long as it may store values greater than the maximum capacity of int and cause int overflow. I failed a submission due to this mistake.**\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n    public long countAlternatingSubarrays(int[] nums) {\n        long ans = 0;\n        int l=0;\n        int r=0;\n        int n=nums.length;\n        while(l<n){\n            if(r<n-1 && nums[r]!=nums[r+1]){\n                while(r<n-1 && nums[r]!=nums[r+1])\n                    r++;\n            }\n            long windowSize = r-l+1;\n            ans += ((windowSize*(windowSize+1))/2);\n            r += 1;\n            l = r;\n        }     \n        return ans;\n    }\n}\n```
['Java']