#2134

Minimum Swaps to Group All 1's Together II

Medium
ArraySliding WindowSliding WindowArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a sliding window approach to efficiently calculate the minimum swaps needed. By keeping track of the number of 1's in a window of size equal to the total number of 1's, we can determine how many swaps are needed in constant time as we slide the window.

⚙️

Algorithm

5 steps
  1. 1Step 1: Count the total number of 1's in the array.
  2. 2Step 2: Create a sliding window of size equal to the total number of 1's.
  3. 3Step 3: Count the number of 1's in the initial window and calculate the swaps needed.
  4. 4Step 4: Slide the window across the array, updating the count of 1's and the swaps needed.
  5. 5Step 5: Keep track of the minimum swaps found.
solution.py15 lines
1# Full working Python code
2
3def minSwaps(nums):
4    total_ones = sum(nums)
5    n = len(nums)
6    nums = nums * 2  # To handle circular nature
7    current_ones = sum(nums[:total_ones])
8    min_swaps = total_ones - current_ones
9
10    for i in range(total_ones, n):
11        current_ones += nums[i] - nums[i - total_ones]
12        swaps = total_ones - current_ones
13        min_swaps = min(min_swaps, swaps)
14
15    return min_swaps

Complexity note: The time complexity is O(n) because we only traverse the array a constant number of times, and the space complexity is O(n) due to the extended array.

  • 1Understanding the circular nature of the array is crucial for solving the problem efficiently.
  • 2Using a sliding window approach allows us to minimize the number of swaps needed in linear time.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.