You are given an integer array, nums, and an integer k. nums comprises of only 0's and 1's. In one move, you can choose two adjacent indices and swap their values.
Return the minimum number of moves required so that nums has k consecutive 1's.
Example 1:
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.
Example 2:
Input: nums = [1,0,0,0,0,0,1,1], k = 3 Output: 5 Explanation: In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1].
Example 3:
Input: nums = [1,1,0,1], k = 2 Output: 0 Explanation: nums already has 2 consecutive 1's.
Constraints:
1 <= nums.length <= 105nums[i] is 0 or 1.1 <= k <= sum(nums)When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a line of lights where some are on and some are off, and you want to gather a specific number of lit lights right next to each other by sliding them back and forth. The brute force strategy involves testing every single possible block of lights in the line, imagining how many moves it would take to gather the required number of lit lights into that specific spot, and doing this for every possible location.
Here's how the algorithm would work step-by-step:
def min_swaps(nums, k):
indices_of_ones = []
for index in range(len(nums)):
if nums[index] == 1:
indices_of_ones.append(index)
# Collect all one positions to evaluate every possible target window placement
total_ones_count = len(indices_of_ones)
if total_ones_count == 0 or k == 0:
return 0
minimum_total_cost = float('inf')
number_of_windows = total_ones_count - k + 1
for window_start in range(number_of_windows):
window_end = window_start + k - 1
median_index = window_start + (k // 2)
median_target_pos = indices_of_ones[median_index]
# Center around the median to minimize total distance for adjacent swaps
current_window_cost = 0
for current_index in range(window_start, window_end + 1):
current_window_cost += abs(indices_of_ones[current_index] - median_target_pos)
offset_adjustment = 0
for offset in range(k):
offset_adjustment += abs(indices_of_ones[window_start + offset] - median_target_pos - (offset - (k // 2)))
if offset_adjustment < minimum_total_cost:
minimum_total_cost = offset_adjustment
# Return the globally minimal swap cost found across all evaluated windows
return minimum_total_costInstead of checking every single possible way to group the ones together, we can use a sliding window approach that focuses on gathering a target number of ones into a tight cluster. By finding the most centered one to act as a permanent anchor point, we can slide our window across the line to efficiently calculate the minimum effort needed to pull all the other ones into place.
Here's how the algorithm would work step-by-step:
def min_moves_to_gather_ones(binary_array, target_ones_count):
ones_indices_list = []
for element_index, element_value in enumerate(binary_array):
if element_value == 1:
ones_indices_list.append(element_index)
total_ones_found = len(ones_indices_list)
minimum_total_distance = float('inf')
prefix_distance_sums = [0]
for position_index in range(total_ones_found):
previous_sum = prefix_distance_sums[-1]
prefix_distance_sums.append(previous_sum + ones_indices_list[position_index])
# Grouping around a central anchor mathematically minimizes total movement distance.
for window_start_index in range(total_ones_found - target_ones_count + 1):
window_end_index = window_start_index + target_ones_count
median_index = window_start_index + target_ones_count // 2
anchor_element_position = ones_indices_list[median_index]
left_count = median_index - window_start_index
right_count = window_end_index - 1 - median_index
left_sum = prefix_distance_sums[median_index] - prefix_distance_sums[window_start_index]
right_sum = prefix_distance_sums[window_end_index] - prefix_distance_sums[median_index + 1]
left_distance_cost = (anchor_element_position * left_count - left_sum) - (left_count * (left_count - 1) // 2)
right_distance_cost = (right_sum - anchor_element_position * right_count) - (right_count * (right_count + 1) // 2)
current_total_distance = left_distance_cost + right_distance_cost
# Tracking the minimum distance ensures we find the most optimal alignment.
if current_total_distance < minimum_total_distance:
minimum_total_distance = current_total_distance
# Returning zero prevents errors if the target cannot be formed.
if minimum_total_distance == float('inf'):
return 0
return minimum_total_distance| Case | How to Handle |
|---|---|
| k equals 1 | The sliding window correctly finds zero swaps needed since a single one is already contiguous with itself. |
| k equals the total number of ones in the array | The algorithm finds the unique window containing all ones and computes the absolute minimum swaps for the entire set. |
| The array has no ones at all | Since the problem implies valid inputs where at least k ones exist, we can assume the constraints guarantee sufficient ones. |
| All ones are already tightly packed together | The distance formula yields zero, resulting in an optimal return value of zero swaps. |
| Maximum possible array length up to one hundred thousand | An O(n) sliding window with prefix sums or a median-based approach ensures the solution executes well within time limits. |
| Large index values leading to integer overflow during position summation | Using 64-bit integers for accumulating positions prevents overflow issues on large arrays. |
| Alternating ones and zeros requiring long-distance movement | The prefix sum or median strategy correctly calculates the absolute distance without missing intermediate elements. |
| Multiple identical minimum swap configurations across different windows | The sliding window evaluates all valid windows of size k and properly retains the global minimum. |