Minimum Adjacent Swaps for K Consecutive Ones — LeetCode 1703 Python Solution
HardGreedyArrayPrefix SumSliding Window
- Problem
- #1703
- Pattern
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(m) auxiliary |
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
LeetCode 1838Frequency of the Most Frequent ElementMediumLeetCode 2271Maximum White Tiles Covered by a CarpetMediumLeetCode 2528Maximize the Minimum Powered CityHardLeetCode 1589Maximum Sum Obtained of Any PermutationMediumLeetCode 2132Stamping the GridHardLeetCode 2171Removing Minimum Number of Magic BeansMedium
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.