C++ 100% Faster | Sliding Window--->O(1) Space | Line By Line Detailed Explanation
\n\n# Intuition\n- An alternating subarray has no consecutive elements with the same value. We can iterate through the array and keep track of the current subar
![Zombie Upvote.png](https://assets.leetcode.com/users/images/69485021-35fe-4983-b71f-d1653883ca6a_1711856055.9033415.png)\n\n# Intuition\n- An alternating subarray has no consecutive elements with the same value. We can iterate through the array and keep track of the current subarray length while checking if adjacent elements differ. If they differ, we can increment the subarray length. Once we encounter two consecutive elements with the same value, we\'ve reached the end of the current subarray.\n- There\'s an interesting fact about counting the number of subarrays of a certain length: the number of subarrays of length k is equal to the sum of 1 + 2 + ... + k. This formula captures the idea that we can choose any starting index within the subarray of length k.\n\n# Approach\n1. **Sliding Window:**\n    - We use a sliding window approach with two pointers (left and right) to track the current subarray.\n2. **Iterate and Check:**\n    - As we iterate through the array using right, we check if the current element (nums[right]) is different from the next element (nums[right + 1]).\n    - If they differ, it\'s part of an alternating subarray, so we increment right to extend the subarray.\n3. **Calculate and Update:**\n    - Once we encounter two consecutive elements with the same value, we\'ve reached the end of the current subarray.\n    - We calculate the number of subarrays within the current subarray length using the formula (length * (length + 1)) / 2. This leverages the fact mentioned in the intuition.\n    - We add this count to the overall count of alternating subarrays.\nWe update the left pointer to right to start a new subarray from the next element.\n\n# Implementation\n- The provided code effectively implements the sliding window approach with the mentioned formula. Here\'s a breakdown:\n\n1. **int countAlternatingSubarrays(vector<int>& nums):** This function takes the binary array nums as input.\n\n2. **int n = nums.size();:** Gets the size of the array n.\n    - **long long count = 0;:** Initializes a variable count to store the total number of alternating subarrays.\n    \n3. **int left = 0;:** Initializes left and right pointers, both starting at index 0.\n\n    - **int right = 0;**\n4. **while (right < n):** A loop that continues as long as right hasn\'t reached the end of the array.\n\n5. **while (right < n - 1 && nums[right] != nums[right + 1]):** This inner loop extends the current subarray as long as adjacent elements differ.\n    - It checks if right is within bounds and if the elements at right and right + 1 are different.\n    - If they differ, we increment right to include the next element in the subarray.\n6. **long long length = right - left + 1;:** Calculates the length of the current subarray (right - left + 1).\n\n7. **count += static_cast<long long>(length * (length + 1)) / 2;:** Calculates the number of subarrays within the current subarray length and adds it to the count.\n\n    - The casting to long long ensures we don\'t overflow for larger length values.\n8. **right++;:** Moves the right pointer forward to start a new subarray from the next element.\n\n9. **left = right;:** Updates the left pointer to the same position as right, effectively starting a new subarray.\n\n10. **return count;:** After the loop finishes iterating through the entire array, count holds the total number of alternating subarrays, which is returned\n\n# Complexity\n- Time complexity **O(n)**\n    - The code iterates through the array at most twice (once in the outer loop and potentially once in the inner loop for each element). This results in a linear time complexity of O(n).\n\n- Space complexity:  **O(1)**\n    - The code uses a constant amount of extra space for variables like count, left, and right, which doesn\'t depend on the input size n.\n\n# Code\n```\n#pragma GCC optimize("03", "unroll-loops")\nclass Solution {\npublic:\n    long long countAlternatingSubarrays(vector<int>& nums) {\n        int n = nums.size();\n        long long count = 0; \n \n        int left = 0;\n        int right = 0;\n        \n        while (right < n) {\n            while (right < n - 1 && nums[right] != nums[right + 1]) {\n                right++;\n            }\n            \n            long long length = right - left + 1;\n        \n            count += static_cast<long long>(length * (length + 1)) / 2;\n        \n            right++;\n            left = right;\n        }\n        \n        return count;\n\n    }\n};\nauto init = [](){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    return \'c\';\n}();\n```\n![Zombie Upvote.png](https://assets.leetcode.com/users/images/9ccc5e2e-0f9c-49ce-97f3-3a4430beb06c_1711856521.4620235.png)\n\n
['Array', 'Sliding Window', 'C++']