Java Solution - Sliding Window
Intuition\n Describe your first thoughts on how to solve this problem. \n- Compare the current element with the previous element. \n- If they are different, inc
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Compare the current element with the previous element. \n- If they are different, increase the length of the window. \n- If they are same, then calculate the number of subarrays that can be created.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Have two pointers, `start` and `end` to keep track of the current window with alternating `0s` and `1s`. The length of the of the current subarray `length` is given by `end - start`.\n- Calculate the number of subarrays that can be formed for any array of length `n` with the following formula.\nn\n\u2211 i = 1 + 2 + 3 + 4 + ... + n = n*(n+1)/2\ni=1\n- Update the `start` of the window and `end` of the window.\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 count = 0;\n        long length = 0;\n        int start = 0;\n        int end = 1;\n        while(end < nums.length) {\n            if(nums[end] != nums[end - 1]) {\n                end++;\n            } else {\n                length = end - start;\n                count += (length * (length + 1)) / 2;\n                start = end;\n                end++;\n            }\n        }\n        length = end - start;\n        count += (length * (length + 1)) / 2;\n        return count;\n    }\n}\n\n```
['Two Pointers', 'Sliding Window', 'Java']