# Minimum number of swaps required such that a given substring consists of exactly K 1s

Finding the minimum number of swaps required for a substring to contain exactly K 1s is a common problem in the realm of computer science and programming. In this article, we will delve deep into this problem and provide a C++ solution for it. This problem has its applications in various domains, including string manipulation, data structure optimization, and coding challenges in interviews.

## Problem Statement

Given a binary string and a number K, the task is to find the minimum number of swaps required to ensure that every substring of the string has exactly K 1s.

## Approach

To tackle this problem, we can use a two-pointer approach along with a sliding window technique. The basic idea is to maintain a window of size K and calculate the number of swaps required to make all 1s in the window.

### Example

Here's a C++ function that implements the above approach −

#include<bits/stdc++.h>
using namespace std;

int minSwaps(string s, int K) {
int n = s.length();
vector<int> onesPrefix(n, 0);
if(s[0] == '1') onesPrefix[0] = 1;

for(int i = 1; i < n; i++) {
onesPrefix[i] = onesPrefix[i-1];
if(s[i] == '1') onesPrefix[i]++;
}

int ans = INT_MAX;
for(int i = 0; i <= n - K; i++) {
int j = i + K - 1;
int ones = onesPrefix[j] - ((i == 0) ? 0 : onesPrefix[i - 1]);
ans = min(ans, K - ones);
}

return ans;
}

int main() {
string s = "10010110";
int K = 3;
cout << "Minimum number of swaps = " << minSwaps(s, K) << endl;
return 0;
}


### Output

Minimum number of swaps = 1


## Test Case Explanation

Let's take the string as "10010110" and K = 3.

In the initial binary string "10010110", we want to make every substring of size 3 have exactly 3 1s. For instance, the substring "100" needs 2 swaps to become "111". Similarly, the substring "001" also needs 2 swaps. By iterating over the string, we find the minimum number of swaps needed is 1 for the substring "101".

## Conclusion

This problem is an excellent example of how an understanding of algorithms, data structures, and the C++ language can come together to solve a complex problem. The understanding and implementation of such problems can be significantly beneficial for software engineers, especially in coding interviews and competitive programming.

Updated on: 18-May-2023

31 Views