#1703
Minimum Adjacent Swaps for K Consecutive Ones
HardArrayGreedySliding WindowPrefix SumSliding WindowGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal 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 number of swaps needed to group k consecutive 1's. This method reduces the time complexity significantly by avoiding redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Identify the positions of all 1's in the array.
- 2Step 2: Use a sliding window of size k to calculate the number of swaps needed to group the 1's.
- 3Step 3: For each window, calculate the cost of moving the 1's to the center of the window and update the minimum swaps.
solution.py15 lines
1# Full working Python code
2
3def min_swaps(nums, k):
4 ones = [i for i in range(len(nums)) if nums[i] == 1]
5 total_ones = len(ones)
6 if total_ones < k:
7 return 0
8 min_swaps = 0
9 for i in range(k):
10 min_swaps += ones[i] - (ones[0] + i)
11 result = min_swaps
12 for i in range(1, total_ones - k + 1):
13 min_swaps += (ones[i + k - 1] - ones[i - 1]) - k
14 result = min(result, min_swaps)
15 return resultℹ
Complexity note: The time complexity is O(n) because we only traverse the array a few times to gather positions of 1's and calculate swaps, making it efficient for larger inputs.
- 1Identifying positions of 1's helps in calculating swaps efficiently.
- 2Using a sliding window reduces the need for redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.