Problem
A swap is defined as taking two distinct positions in an array and swapping the values in them.
A circular array is defined as an array where we consider the first element and the last element to be adjacent.
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.
Examples
Example 1:
| |
Example 2:
| |
Example 3:
| |
Solution
Method 1 - Sliding Window
We can do following:
- Counting 1’s: First, count the total number of
1s in the array. Let’s denote this count astotalOnes. So, that we know the condition that all ones are now together. - Sliding Window: Use a sliding window of size
totalOnesto find the minimum number of0s in any window of that size. This will help us determine how many swaps are needed to bring all1s together. - Circular Array Handling: To handle the circular nature of the array, we can extend the array by concatenating it with itself. This allows us to use a straightforward sliding window approach.
Here are the steps:
- Count the total number of
1s,totalOnes. - Extend the array by concatenating it with itself.
- Apply a sliding window of size
totalOnesto count the number of0s in each window, and keep track of the minimum count of0s. - The answer will be the minimum count of
0s found in the windows, as this represents the minimum number of swaps needed.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n), wherenis length of the array - 🧺 Space complexity:
O(n)for using exended array
Method 2 - Without using extra space with % operator
Code
| |
Complexity
- ⏰ Time complexity:
O(n), wherenis length of the array - 🧺 Space complexity:
O(1)for using exended array