2134. Minimum Swaps to Group All 1's Together II Medium
1/**
2 * [2134] Minimum Swaps to Group All 1's Together II
3 *
4 * A swap is defined as taking two distinct positions in an array and swapping the values in them.
5 * A circular array is defined as an array where we consider the first element and the last element to be adjacent.
6 * Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location.
7 *
8 * Example 1:
9 *
10 * Input: nums = [0,1,0,1,1,0,0]
11 * Output: 1
12 * Explanation: Here are a few of the ways to group all the 1's together:
13 * [0,<u>0</u>,<u>1</u>,1,1,0,0] using 1 swap.
14 * [0,1,<u>1</u>,1,<u>0</u>,0,0] using 1 swap.
15 * [1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array).
16 * There is no way to group all 1's together with 0 swaps.
17 * Thus, the minimum number of swaps required is 1.
18 *
19 * Example 2:
20 *
21 * Input: nums = [0,1,1,1,0,0,1,1,0]
22 * Output: 2
23 * Explanation: Here are a few of the ways to group all the 1's together:
24 * [1,1,1,0,0,0,0,1,1] using 2 swaps (using the circular property of the array).
25 * [1,1,1,1,1,0,0,0,0] using 2 swaps.
26 * There is no way to group all 1's together with 0 or 1 swaps.
27 * Thus, the minimum number of swaps required is 2.
28 *
29 * Example 3:
30 *
31 * Input: nums = [1,1,0,0,1]
32 * Output: 0
33 * Explanation: All the 1's are already grouped together due to the circular property of the array.
34 * Thus, the minimum number of swaps required is 0.
35 *
36 *
37 * Constraints:
38 *
39 * 1 <= nums.length <= 10^5
40 * nums[i] is either 0 or 1.
41 *
42 */
43pub struct Solution {}
44
45// problem: https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/
46// discuss: https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/discuss/?currentPage=1&orderBy=most_votes&query=
47
48// submission codes start here
49
50impl Solution {
51 pub fn min_swaps(nums: Vec<i32>) -> i32 {
52 0
53 }
54}
55
56// submission codes end
57
58#[cfg(test)]
59mod tests {
60 use super::*;
61
62 #[test]
63 fn test_2134() {
64 }
65}
66
Back
© 2025 bowen.ge All Rights Reserved.