1248. Count Number of Nice Subarrays - Brute Force & Sliding Window Approaches
Brute Force - Memory Limit Exceeded\r\n\r\nclass Solution:\r\n    def numberOfSubarrays(self, nums: List[int], k: int) -> int:\r\n        def countOdds(arr): # 
## Brute Force - Memory Limit Exceeded\r\n```\r\nclass Solution:\r\n    def numberOfSubarrays(self, nums: List[int], k: int) -> int:\r\n        def countOdds(arr): # Function to Count Odd Values in Arr.\r\n            odds = 0\r\n            for i in range(len(arr)):\r\n                if arr[i] % 2 != 0:\r\n                    odds += 1\r\n            return odds\r\n\r\n        # Main\r\n        n = len(nums)\r\n        all_subarrs = [] # Stores all SubArrays\r\n        for i in range(n):\r\n            for j in range(i, n):\r\n                all_subarrs.append(nums[i:j+1]) \r\n        print(all_subarrs)\r\n\r\n        # To check whether all SubArrays are Stored are Not\r\n        # if len(all_subarrs) == n * (n + 1) / 2:\r\n            # print(\'Correct\')\r\n\r\n        ans = 0\r\n        # Traversing through each SubArr\r\n        for sub_arr in all_subarrs:\r\n            if countOdds(sub_arr) == k:\r\n                ans += 1\r\n\r\n        return ans\r\n```\r\n\r\n---\r\n\r\n## Sliding Window - TC : O(N) , SC : O(1)\r\n```\r\nclass Solution:\r\n    def numberOfSubarrays(self, nums: List[int], k: int) -> int:\r\n        left = right = 0\r\n        ans = 0 # Ans is final Answer\r\n        count = 0 # Count is used for Counting all SubArrays when Condition got Satisified\r\n        odds = 0 # Counts No. of Odds in Current Window\r\n\r\n        while right < len(nums):\r\n            if nums[right] % 2 != 0: # Odd\r\n                odds += 1\r\n                count = 0\r\n            \r\n            while odds == k: \r\n                # Try to Move the Left Pointer \r\n                # Also, Increment the Count Variable as We can have One More SubArr, satisfying the Condition\r\n                if nums[left] % 2 == 0: # Even\r\n                    count += 1\r\n                \r\n                if nums[left] % 2 != 0: # Odd \r\n                    odds -= 1\r\n                    count += 1\r\n                \r\n                left += 1\r\n            \r\n            ans += count\r\n\r\n            right += 1\r\n        return ans\r\n```\r\n**Please UpVote**
['Array', 'Sliding Window', 'Python3']