Skip to content

Commit 29289f6

Browse files
authored
Merge pull request #1552 from SadafKausar2025/cas
Addeing leetcode-3101 count Alternate subarrays
2 parents d8eccaa + 313efb2 commit 29289f6

File tree

2 files changed

+257
-1
lines changed

2 files changed

+257
-1
lines changed

dsa-problems/leetcode-problems/3100-3199.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ export const problems = [
2020
"problemName": "3101. Count Alternating Subarrays",
2121
"difficulty": "Medium",
2222
"leetCodeLink": "https://leetcode.com/problems/count-alternating-subarrays",
23-
"solutionLink": "#"
23+
"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/Count-Alternating-subarrays"
2424
},
2525
{
2626
"problemName": "3102. Minimize Manhattan Distances",
Lines changed: 256 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,256 @@
1+
---
2+
id: Count-Alternating-subarrays
3+
title: Count-Alternating-subarrays
4+
level: hard
5+
sidebar_label: Count-Alternating-subarrays
6+
tags:
7+
- Dynamic Programming
8+
- Bit Manipulation
9+
- C++
10+
- Java
11+
- Python
12+
description: "This document provides solutions for Count-Alternating-subarrays solution of leetcode questions"
13+
---
14+
15+
## Problem statement:
16+
17+
You are given a binary array nums.
18+
19+
We call a subarray alternating if no two adjacent elements in the subarray have the same value.
20+
21+
Return the number of alternating subarrays in nums.
22+
23+
**Example 1:**
24+
25+
Input: nums = [0,1,1,1]
26+
Output: 5
27+
28+
Explanation:
29+
The following subarrays are alternating: [0], [1], [1], [1], and [0,1].
30+
31+
**Example 2:**
32+
33+
Input: nums = [1,0,1,0]
34+
Output: 10
35+
36+
Explanation:
37+
Every subarray of the array is alternating. There are 10 possible subarrays that we can choose.
38+
39+
Constraints:
40+
41+
- `1 <= nums.length <= 105`
42+
- `nums[i] is either 0 or 1.`
43+
44+
## Solutions:
45+
46+
### Intuition
47+
48+
- 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.
49+
50+
- 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.
51+
52+
### Approach
53+
54+
1. **Sliding Window:**
55+
56+
- We use a sliding window approach with two pointers (left and right) to track the current subarray.
57+
58+
2. **Iterate and Check:**
59+
60+
- 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]).
61+
62+
- If they differ, it's part of an alternating subarray, so we increment right to extend the subarray.
63+
64+
3. **Calculate and Update:**
65+
66+
- Once we encounter two consecutive elements with the same value, we've reached the end of the current subarray.
67+
68+
- 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.
69+
70+
- We add this count to the overall count of alternating subarrays.
71+
72+
- We update the left pointer to right to start a new subarray from the next element.
73+
74+
### Implementation
75+
76+
The provided code effectively implements the sliding window approach with the mentioned formula. Here's a breakdown:
77+
78+
1. int countAlternatingSubarrays(vector& nums): This function takes the binary array nums as input.
79+
80+
2. int n = nums.size();: Gets the size of the array n.
81+
82+
3. long long count = 0;: Initializes a variable count to store the total number of alternating subarrays.
83+
84+
4. int left = 0;: Initializes left and right pointers, both starting at index 0.
85+
86+
87+
- int right = 0;
88+
89+
5. while (right < n): A loop that continues as long as right hasn't reached the end of the array.
90+
91+
92+
- while (right < n - 1 && nums[right] != nums[right + 1]): This inner loop extends the current subarray as long as adjacent elements differ.
93+
94+
6. It checks if right is within bounds and if the elements at right and right + 1 are different.
95+
96+
7. If they differ, we increment right to include the next element in the subarray.
97+
long long length = right - left + 1;: Calculates the length of the current subarray (right - left + 1).
98+
99+
8. count += static_cast(length \* (length + 1)) / 2;: Calculates the number of subarrays within the current subarray length and adds it to the count.
100+
101+
9. The casting to long long ensures we don't overflow for larger length values.
102+
103+
- right++;: Moves the right pointer forward to start a new subarray from the next element.
104+
105+
- left = right;: Updates the left pointer to the same position as right, effectively starting a new subarray.
106+
107+
10. return count;: After the loop finishes iterating through the entire array, count holds the total number of alternating subarrays, which is returned
108+
109+
## Code
110+
111+
<Tabs>
112+
<TabItem value="cpp" label="C++" default>
113+
<SolutionAuthor name="@Ajay-Dhangar"/>
114+
```cpp
115+
class Solution {
116+
public:
117+
long long countAlternatingSubarrays(vector<int>& nums) {
118+
int n = nums.size();
119+
long long count = 0;
120+
121+
int left = 0;
122+
int right = 0;
123+
124+
while (right < n) {
125+
while (right < n - 1 && nums[right] != nums[right + 1]) {
126+
right++;
127+
}
128+
129+
long long length = right - left + 1;
130+
131+
count += static_cast<long long>(length * (length + 1)) / 2;
132+
133+
right++;
134+
left = right;
135+
}
136+
137+
return count;
138+
}
139+
};
140+
```
141+
</TabItem>
142+
<TabItem value="java" label="Java">
143+
<SolutionAuthor name="@Ajay-Dhangar"/>
144+
```java
145+
public class Solution {
146+
public long countAlternatingSubarrays(int[] nums) {
147+
int n = nums.length;
148+
long count = 0;
149+
150+
int left = 0;
151+
int right = 0;
152+
153+
while (right < n) {
154+
while (right < n - 1 && nums[right] != nums[right + 1]) {
155+
right++;
156+
}
157+
158+
long length = right - left + 1;
159+
160+
count += (length * (length + 1)) / 2;
161+
162+
right++;
163+
left = right;
164+
}
165+
166+
return count;
167+
}
168+
169+
// Driver code
170+
public static void main(String[] args) {
171+
Solution sol = new Solution();
172+
int[] nums = {1, 0, 1, 0, 1};
173+
System.out.println(sol.countAlternatingSubarrays(nums)); // Output: 9
174+
}
175+
}
176+
```
177+
</TabItem>
178+
<TabItem value="python" label="Python">
179+
<SolutionAuthor name="@Ajay-Dhangar"/>
180+
```python
181+
class Solution:
182+
def countAlternatingSubarrays(self, nums):
183+
n = len(nums)
184+
count = 0
185+
186+
left = 0
187+
right = 0
188+
189+
while right < n:
190+
while right < n - 1 and nums[right] != nums[right + 1]:
191+
right += 1
192+
193+
length = right - left + 1
194+
195+
count += (length * (length + 1)) // 2
196+
197+
right += 1
198+
left = right
199+
200+
return count
201+
202+
# Driver code
203+
if __name__ == "__main__":
204+
sol = Solution()
205+
nums = [1, 0, 1, 0, 1]
206+
print(sol.countAlternatingSubarrays(nums)) # Output: 9
207+
```
208+
</TabItem>
209+
<TabItem value="c" label="C">
210+
<SolutionAuthor name="@Ajay-Dhangar"/>
211+
```c
212+
#include <stdio.h>
213+
214+
long long countAlternatingSubarrays(int* nums, int n) {
215+
long long count = 0;
216+
217+
int left = 0;
218+
int right = 0;
219+
220+
while (right < n) {
221+
while (right < n - 1 && nums[right] != nums[right + 1]) {
222+
right++;
223+
}
224+
225+
long long length = right - left + 1;
226+
227+
count += (length * (length + 1)) / 2;
228+
229+
right++;
230+
left = right;
231+
}
232+
233+
return count;
234+
}
235+
236+
// Driver code
237+
int main() {
238+
int nums[] = {1, 0, 1, 0, 1};
239+
int n = sizeof(nums) / sizeof(nums[0]);
240+
printf("%lld\n", countAlternatingSubarrays(nums, n)); // Output: 9
241+
return 0;
242+
}
243+
```
244+
</TabItem>
245+
246+
</Tabs>
247+
248+
## Complexity
249+
250+
### Time complexity: $O(n)$
251+
252+
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)$.
253+
254+
### Space complexity: $O(1)$
255+
256+
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.

0 commit comments

Comments
 (0)