All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : March 01, 2025
Last updated : March 01, 2025
Related Topics : Array, Sliding Window
Acceptance Rate : 61.09 %
Initial decently performing prefix sum + sliding window attempt.
Optimized window finding by using a max function
Optimized further (though at the expense of no longer being
space) by using itertools.accumulate
to get the prefix sum.Note: Built in functions are almost always more efficiently implemented due to them falling back on
C
.
class Solution:
def minSwaps(self, data: List[int]) -> int:
# convert data into a prefix sum starting at zero
running_total = 0
for i in range(len(data)) :
data[i], running_total = running_total, running_total + data[i]
data.append(running_total)
tot_ones = data[-1]
# Find window of size tot_ones with the most ones already there
output = 0
for i in range(tot_ones, len(data)) :
output = max(output, data[i] - data[i - tot_ones])
return tot_ones - output
class Solution:
def minSwaps(self, data: List[int]) -> int:
# convert data into a prefix sum starting at zero
running_total = 0
for i in range(len(data)) :
data[i], running_total = running_total, running_total + data[i]
data.append(running_total)
tot_ones = data[-1]
return min(tot_ones - (data[i] - data[i - tot_ones]) for i in range(tot_ones, len(data)))
class Solution:
def minSwaps(self, data: List[int]) -> int:
data = [0] + list(accumulate(data))
tot_ones = data[-1]
return tot_ones - max(data[i + tot_ones] - data[i] for i in range(len(data) - tot_ones))