#3101
Count Alternating Subarrays
MediumApproaches
💡
Intuition
Time O(n²)Space O(1)
The brute-force approach involves checking every possible subarray to see if it's alternating. This is straightforward but inefficient, as it requires examining all pairs of start and end indices.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a variable to count the number of alternating subarrays.
- 2Step 2: Use two nested loops to iterate through all possible subarrays.
- 3Step 3: For each subarray, check if it is alternating by comparing adjacent elements.
- 4Step 4: If it is alternating, increment the count.
solution.py13 lines
1# Full working Python code
2
3def countAlternatingSubarrays(nums):
4 count = 0
5 n = len(nums)
6 for i in range(n):
7 for j in range(i, n):
8 if all(nums[k] != nums[k + 1] for k in range(i, j)):
9 count += 1
10 return count
11
12# Example usage
13print(countAlternatingSubarrays([0, 1, 1, 1])) # Output: 5ℹ
Complexity note: This complexity arises because we are using two nested loops to check every possible subarray, leading to O(n²) comparisons.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.