Skip to content

Commit 253b09c

Browse files
committed
[LeetCode Sync] Runtime - 54 ms (63.14%), Memory - 21.4 MB (99.40%)
1 parent 50f5209 commit 253b09c

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p>
2+
3+
<p>We call a <span data-keyword="subarray-nonempty">subarray</span> <strong>alternating</strong> if <strong>no</strong> two <strong>adjacent</strong> elements in the subarray have the <strong>same</strong> value.</p>
4+
5+
<p>Return <em>the number of alternating subarrays in </em><code>nums</code>.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
10+
<div class="example-block">
11+
<p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1]</span></p>
12+
13+
<p><strong>Output:</strong> <span class="example-io">5</span></p>
14+
15+
<p><strong>Explanation:</strong></p>
16+
17+
<p>The following subarrays are alternating: <code>[0]</code>, <code>[1]</code>, <code>[1]</code>, <code>[1]</code>, and <code>[0,1]</code>.</p>
18+
</div>
19+
20+
<p><strong class="example">Example 2:</strong></p>
21+
22+
<div class="example-block">
23+
<p><strong>Input:</strong> <span class="example-io">nums = [1,0,1,0]</span></p>
24+
25+
<p><strong>Output:</strong> <span class="example-io">10</span></p>
26+
27+
<p><strong>Explanation:</strong></p>
28+
29+
<p>Every subarray of the array is alternating. There are 10 possible subarrays that we can choose.</p>
30+
</div>
31+
32+
<p>&nbsp;</p>
33+
<p><strong>Constraints:</strong></p>
34+
35+
<ul>
36+
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
37+
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
38+
</ul>
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
class Solution:
2+
def countAlternatingSubarrays(self, nums: List[int]) -> int:
3+
result = 1
4+
sum_val = 1
5+
for val1, val2 in pairwise(nums):
6+
sum_val = sum_val + 1 if val1 != val2 else 1
7+
result += sum_val
8+
9+
return result

0 commit comments

Comments
 (0)