HardNo. 1703
Minimum Adjacent Swaps for K Consecutive Ones — LeetCode 1703 Python Solution
- Pattern
- Sliding Window
- Topics
- Greedy, Array, Prefix Sum, Sliding Window
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given an integer array, nums, and an integer k. nums comprises of only 0's and 1's.
Example
- Input
- nums = [1,0,0,1,0,1], k = 2
- Output
- 1
- Explanation
- In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's.
Python solution
class Solution:
def minMoves(self, nums: List[int], k: int) -> int:
arr = [i for i, x in enumerate(nums) if x]
s = list(accumulate(arr, initial=0))
ans = inf
x = (k + 1) // 2
y = k - x
for i in range(x - 1, len(arr) - y):
j = arr[i]
ls = s[i + 1] - s[i + 1 - x]
rs = s[i + 1 + y] - s[i + 1]
a = (j + j - x + 1) * x // 2 - ls
b = rs - (j + 1 + j + y) * y // 2
ans = min(ans, a + b)
return ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(m)
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1703. Minimum Adjacent Swaps for K Consecutive Ones is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1838 | Frequency of the Most Frequent Element | Medium |
| 2271 | Maximum White Tiles Covered by a Carpet | Medium |
| 2528 | Maximize the Minimum Powered City | Hard |
| 1589 | Maximum Sum Obtained of Any Permutation | Medium |
| 2132 | Stamping the Grid | Hard |
| 2171 | Removing Minimum Number of Magic Beans | Medium |
Frequently asked questions
- How hard is LeetCode 1703. Minimum Adjacent Swaps for K Consecutive Ones?
LeetCode 1703. Minimum Adjacent Swaps for K Consecutive Ones is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1703. Minimum Adjacent Swaps for K Consecutive Ones?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1703. Minimum Adjacent Swaps for K Consecutive Ones?
The Python solution on this page uses O(m) auxiliary space.
- What topics does LeetCode 1703. Minimum Adjacent Swaps for K Consecutive Ones cover?
LeetCode 1703. Minimum Adjacent Swaps for K Consecutive Ones is tagged Greedy, Array, Prefix Sum and Sliding Window on LeetCode.