Skip to content

Commit 15636d4

Browse files
committed
Add solution #3208
1 parent 44acf5a commit 15636d4

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -820,6 +820,7 @@
820820
3151|[Special Array I](./3151-special-array-i.js)|Easy|
821821
3160|[Find the Number of Distinct Colors Among the Balls](./3160-find-the-number-of-distinct-colors-among-the-balls.js)|Medium|
822822
3174|[Clear Digits](./3174-clear-digits.js)|Easy|
823+
3208|[Alternating Groups II](./3208-alternating-groups-ii.js)|Medium|
823824
3223|[Minimum Length of String After Operations](./3223-minimum-length-of-string-after-operations.js)|Medium|
824825
3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy|
825826
3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy|
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* 3208. Alternating Groups II
3+
* https://leetcode.com/problems/alternating-groups-ii/
4+
* Difficulty: Medium
5+
*
6+
* There is a circle of red and blue tiles. You are given an array of integers colors and
7+
* an integer k. The color of tile i is represented by colors[i]:
8+
* - colors[i] == 0 means that tile i is red.
9+
* -colors[i] == 1 means that tile i is blue.
10+
*
11+
* An alternating group is every k contiguous tiles in the circle with alternating colors
12+
* (each tile in the group except the first and last one has a different color from its
13+
* left and right tiles).
14+
*
15+
* Return the number of alternating groups.
16+
*
17+
* Note that since colors represents a circle, the first and the last tiles are considered
18+
* to be next to each other.
19+
*/
20+
21+
/**
22+
* @param {number[]} colors
23+
* @param {number} k
24+
* @return {number}
25+
*/
26+
var numberOfAlternatingGroups = function(colors, k) {
27+
const extended = colors.concat(colors.slice(0, k - 1));
28+
let result = 0;
29+
let invalid = 0;
30+
31+
for (let i = 1; i < k; i++) {
32+
if (extended[i] === extended[i - 1]) {
33+
invalid++;
34+
}
35+
}
36+
if (invalid === 0) {
37+
result++;
38+
}
39+
for (let i = 1; i < colors.length; i++) {
40+
if (extended[i] === extended[i - 1]) invalid--;
41+
if (extended[i + k - 1] === extended[i + k - 2]) invalid++;
42+
if (invalid === 0) result++;
43+
}
44+
45+
return result;
46+
};

0 commit comments

Comments
 (0)