File tree 2 files changed +40
-1
lines changed
2 files changed +40
-1
lines changed Original file line number Diff line number Diff line change 1
- # 1,768 LeetCode solutions in JavaScript
1
+ # 1,769 LeetCode solutions in JavaScript
2
2
3
3
[ https://leetcodejavascript.com ] ( https://leetcodejavascript.com )
4
4
1635
1635
2131|[ Longest Palindrome by Concatenating Two Letter Words] ( ./solutions/2131-longest-palindrome-by-concatenating-two-letter-words.js ) |Medium|
1636
1636
2132|[ Stamping the Grid] ( ./solutions/2132-stamping-the-grid.js ) |Hard|
1637
1637
2133|[ Check if Every Row and Column Contains All Numbers] ( ./solutions/2133-check-if-every-row-and-column-contains-all-numbers.js ) |Easy|
1638
+ 2134|[ Minimum Swaps to Group All 1's Together II] ( ./solutions/2134-minimum-swaps-to-group-all-1s-together-ii.js ) |Medium|
1638
1639
2140|[ Solving Questions With Brainpower] ( ./solutions/2140-solving-questions-with-brainpower.js ) |Medium|
1639
1640
2145|[ Count the Hidden Sequences] ( ./solutions/2145-count-the-hidden-sequences.js ) |Medium|
1640
1641
2154|[ Keep Multiplying Found Values by Two] ( ./solutions/2154-keep-multiplying-found-values-by-two.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 2134. Minimum Swaps to Group All 1's Together II
3
+ * https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/
4
+ * Difficulty: Medium
5
+ *
6
+ * A swap is defined as taking two distinct positions in an array and swapping the values in them.
7
+ *
8
+ * A circular array is defined as an array where we consider the first element and the last element
9
+ * to be adjacent.
10
+ *
11
+ * Given a binary circular array nums, return the minimum number of swaps required to group all
12
+ * 1's present in the array together at any location.
13
+ */
14
+
15
+ /**
16
+ * @param {number[] } nums
17
+ * @return {number }
18
+ */
19
+ var minSwaps = function ( nums ) {
20
+ const onesCount = nums . reduce ( ( sum , num ) => sum + num , 0 ) ;
21
+ const n = nums . length ;
22
+ let result = Infinity ;
23
+ let currentZeros = 0 ;
24
+
25
+ for ( let i = 0 ; i < onesCount ; i ++ ) {
26
+ if ( nums [ i ] === 0 ) currentZeros ++ ;
27
+ }
28
+
29
+ result = currentZeros ;
30
+
31
+ for ( let i = 1 ; i < n ; i ++ ) {
32
+ if ( nums [ ( i - 1 ) % n ] === 0 ) currentZeros -- ;
33
+ if ( nums [ ( i + onesCount - 1 ) % n ] === 0 ) currentZeros ++ ;
34
+ result = Math . min ( result , currentZeros ) ;
35
+ }
36
+
37
+ return result ;
38
+ } ;
You can’t perform that action at this time.
0 commit comments