Simple and easy solution with comments, beats 90% ✅✅
\n\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\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 {\npublic:\n    // long long countAlternatingSubarrays(vector<int>& arr) {\n    //     int i = 0 , j = 0, n = arr.size();\n    //     long long ans = 0;\n\n    //     while(j < n){\n    //         // check if j+1 < n, otherwise index out of bound here\n    //         if(j+1 < n && arr[j] != arr[j+1]){\n    //             j++;\n    //         }\n    //         // case of j == n-1 will be handeled here\n    //         else{\n    //             long long len = j - i + 1;\n    //             ans = ans + (len*(len+1))/2;\n    //             j++;\n    //             i = j;\n    //         }\n    //     }\n    //     return ans;\n    // }\n\n\n    // same logic using while loop\n    long long countAlternatingSubarrays(vector<int>& arr) {\n        int i = 0 , j = 0, n = arr.size();\n        long long ans = 0;\n\n        while(j < n){\n            // check if j+1 < n, otherwise index out of bound here\n            while(j+1 < n && arr[j] != arr[j+1]){\n                j++;\n            }\n            long long len = j - i + 1;\n            ans = ans + (len*(len+1))/2;\n            j++;\n            i = j;\n        }\n        return ans;\n    }\n};\n```
['C++']