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
1
s 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
totalOnes
to find the minimum number of0
s in any window of that size. This will help us determine how many swaps are needed to bring all1
s 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
1
s,totalOnes
. - Extend the array by concatenating it with itself.
- Apply a sliding window of size
totalOnes
to count the number of0
s in each window, and keep track of the minimum count of0
s. - The answer will be the minimum count of
0
s found in the windows, as this represents the minimum number of swaps needed.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is 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)
, wheren
is length of the array - 🧺 Space complexity:
O(1)
for using exended array