Taro Logo

Minimum Adjacent Swaps for K Consecutive Ones

#198 Most AskedHard
0 views
Topics:
ArraysSliding WindowsGreedy Algorithms

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 <= 105
  • nums[i] is 0 or 1.
  • 1 <= k <= sum(nums)

Solution


Clarifying Questions

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:

  1. What are the constraints on the length of the binary array `nums` and the value of `k`?
  2. Is it guaranteed that the array will contain at least `k` ones, or should we handle cases where total ones are less than `k`?
  3. Can `k` be greater than the total number of ones present in the entire array?
  4. Since the array is binary, do we only need to worry about moving the `k` ones, or can elements be modified/mutated rather than just swapped?
  5. If there are multiple ways to achieve the minimum adjacent swaps, does it matter which valid grouping we pick?

Brute Force Solution

Approach

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:

  1. Look at the entire row of lights from start to finish.
  2. Pick a target window of a size equal to the number of lit lights you need to gather.
  3. Slide this window so that it covers every possible grouping of that size from the very beginning to the very end of the row.
  4. For each possible window location, look at all the lit lights that fall outside of this window.
  5. Count how many steps it would take to slide each of those stray lit lights so they fit neatly inside your chosen window.
  6. Add up all these sliding steps to get a total cost for that specific window location.
  7. Repeat this counting process for every possible window location across the entire row.
  8. Compare the total costs from all the different window locations you tested.
  9. Declare the absolute lowest total cost as your final answer.

Code Implementation

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_cost

Big(O) Analysis

Time Complexity
O(n²) – We iterate through every possible window location of size K across the array of n elements, resulting in n minus K plus one window placements. For each of these window locations, we iterate across the elements within the window to calculate the sliding distance cost for the lit lights. This means we perform a nested traversal where each window check takes up to K steps, leading to approximately n times K operations. In the worst case where K is proportional to n, this scales to n squared operations, simplifying to O(n²).
Space Complexity
O(N) – To implement the strategy of gathering lit lights, we first extract the indices of all lit lights from the input array into a separate list of size N, where N is the total number of elements. We then construct a prefix sum array of size N to efficiently calculate the sliding steps required for any target window. These auxiliary collections dominate the memory usage, scaling directly with the number of lights in the row. Beyond these data structures, only a few primitive integer variables are used to keep track of the minimum cost and loop indices. Thus, the total auxiliary space complexity simplifies to Big O of N.

Optimal Solution

Approach

Instead 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:

  1. Scan through the entire line and make a clean list of all the exact locations where the ones currently sit.
  2. Visualize a sliding window that is wide enough to hold your target number of ones.
  3. Slide this window across your list of locations, stopping at every possible group of the correct size.
  4. For any chosen group, imagine picking the one sitting right in the middle to act as your anchor point, because gathering the ones around a central point always takes the least amount of movement.
  5. Calculate the total distance the surrounding ones need to travel to sit directly next to each other right around that anchor point.
  6. Keep track of the smallest total distance found as your window glides smoothly from the start of the line to the end.
  7. Return the smallest total movement calculated, which represents the fewest adjacent swaps required to get your consecutive ones.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n) – First, a single linear scan through the input array of size n collects all the indices of the ones, taking O(n) time. Next, we slide a window of size k across these collected indices, performing a constant-time distance calculation for each of the n - k + 1 possible windows. Since each index is added and removed from the sliding window at most once, this second phase also runs in linear time. Combining the initial scan and the sliding window traversal, the total operations scale linearly with n, which simplifies to O(n).
Space Complexity
O(N) – The algorithm requires auxiliary space primarily driven by the initial scan of the array, where we store the exact indices of all ones in a temporary list. Letting N represent the total number of elements in the input, this list of positions can grow up to size N in the worst-case scenario where all elements are ones. Beyond this list, only a few primitive variables are used to maintain the sliding window boundaries and track the minimum distance. Therefore, the extra memory usage scales linearly with the input size, simplifying to Big O of N space complexity.

Edge Cases

k equals 1
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
The distance formula yields zero, resulting in an optimal return value of zero swaps.
Maximum possible array length up to one hundred thousand
How to Handle:
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
How to Handle:
Using 64-bit integers for accumulating positions prevents overflow issues on large arrays.
Alternating ones and zeros requiring long-distance movement
How to Handle:
The prefix sum or median strategy correctly calculates the absolute distance without missing intermediate elements.
Multiple identical minimum swap configurations across different windows
How to Handle:
The sliding window evaluates all valid windows of size k and properly retains the global minimum.
0/257 completed