Problem
A swap is defined as taking two distinct positions in an array and swapping the values in them.
Given a binary 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
The idea is to find the smallest number of swaps required to group all 1
s together in any position within the array.
Approach
- Count
1
s: First, count the total number of1
s in the array, denoted astotalOnes
. - Sliding Window: Use a sliding window of size
totalOnes
to find the minimum number of0
s in any window of that size. The number of swaps needed will be equal to the number of0
s in the optimal window.
Steps
- Count the total number of
1
s,totalOnes
. - 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 the length of the array - 🧺 Space complexity:
O(1)