Fewest Arbitrary Swaps for One Block of Ones

Quick Overview

Fewest Arbitrary Swaps for One Block of Ones. In the binary array data, swap any two positions per operation.

Fewest Arbitrary Swaps for One Block of Ones

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem In the binary array data, swap any two positions per operation. Return the minimum swaps needed so every 1 lies in one contiguous block somewhere in the array. This is a linear array, not a circular one. ```cpp class Solution { public: int minSwaps(vector<int>& data); }; ``` ### Examples **Example 1:** ```text Input: data = [1,0,0,1] Output: 1 Explanation: Swap the first1 with the zero immediately before the last1 to get[0,0,1,1]. ``` **Example 2:** ```text Input: data = [0,0] Output: 0 Explanation: With no1s, nothing needs moving. ``` ### Constraints - The array length is between 1 and 100000. - Every entry is 0 or 1. ### Contract considerations Return a count, not a rearranged array or swap sequence. ```hint Read the boundary condition Are swaps restricted to neighboring positions, and may the destination block wrap around the array ends? ``` ### Boundary reminders Return a count, not a rearranged array or swap sequence.

Overview: Fewest Arbitrary Swaps for One Block of Ones. In the binary array data, swap any two positions per operation.

Amazon logo
Amazon
Jun 17, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

In the binary array data, swap any two positions per operation. Return the minimum swaps needed so every 1 lies in one contiguous block somewhere in the array. This is a linear array, not a circular one.

class Solution {
public:
    int minSwaps(vector<int>& data);
};

Examples

Example 1:

Input: data = [1,0,0,1]
Output: 1
Explanation: Swap the first1 with the zero immediately before the last1 to get[0,0,1,1].

Example 2:

Input: data = [0,0]
Output: 0
Explanation: With no1s, nothing needs moving.

Constraints

  • The array length is between 1 and 100000.
  • Every entry is 0 or 1.

Contract considerations

Return a count, not a rearranged array or swap sequence.

Boundary reminders

Return a count, not a rearranged array or swap sequence.